<%@ 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(){//回调函数，在编辑和保存动作时，供openDialog调用提交表单。
		  if(validateForm.form()){

              if($("#settleDetailList tr:visible").length==0){
                  top.layer.alert('请至少添加一条结算明细！', {icon: 0});
                  return false;
              }

			  $("#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/save" 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">结算部门：</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"  maxlength="255"  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 nav-btns">
                        <a class="nav-btn nav-btn-add" onclick="addRow('#settleDetailList', settleDetailIdx, settleDetailTpl);"><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 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>
                                <th width="8%">操作</th>
                            </tr>
                            </thead>
                            <tbody id="settleDetailList">
                            </tbody>
                        </table>
                        <script type="text/template" id="settleDetailTpl">//<!--
                            <tr id="settleDetailList{{idx}}">
                            <td class="hide">
                            <input id="settleDetailList{{idx}}_id" name="settleDetailList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
                            <input id="settleDetailList{{idx}}_delFlag" name="settleDetailList[{{idx}}].delFlag" type="hidden" value="0"/>
                            </td>
                            <td>
                                <sys:gridselectInvoice url="${ctx}/workreceipts/workReceiptsSettle/selectinvoice" type="" isTotal="1" id="settleDetailList{{idx}}_invoice" name="settleDetailList[{{idx}}].invoice.id"  value="{{row.invoice.id}}"  title="选择发票" labelName="settleDetailList[{{idx}}].invoice.number"
                                                      companyId="${workReceiptsSettle.office.id}"  idx="{{idx}}"	labelValue="{{row.invoice.number}}" cssClass="form-control required" fieldLabels="发票编号" fieldKeys="number" searchLabel="发票编号" searchKey="number" ></sys:gridselectInvoice>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_invoiceAmt" name="settleDetailList[{{idx}}].invoice.totalMoney" type="text" value="{{row.invoice.totalMoney}}" onchange="formatNum(this);" readOnly="true"  class="form-control money"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_taxMoney" name="settleDetailList[{{idx}}].invoice.taxMoney" type="text" value="{{row.invoice.taxMoney}}" onchange="formatNum(this);" readOnly="true"  class="form-control money"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_incomeAmt" name="settleDetailList[{{idx}}].invoice.incomeMoney" type="text" value="{{row.invoice.incomeMoney}}" onchange="formatNum(this);" readOnly="true"  class="form-control required money"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_settlePct" name="settleDetailList[{{idx}}].settlePct" type="text" value="{{row.settlePct}}"  onchange="caculateAmt('#settleDetailList{{idx}}_');" class="form-control required percent"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_settleAmt" type="text" value="{{row.settleAmt}}" onchange="formatNum(this);" readOnly="true"  class="form-control required money"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_project" type="text" value="{{row.invoice.workInvoice.project.projectName}}"  readOnly="true"  class="form-control"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_contract" type="text" value="{{row.invoice.workInvoice.project.workContractInfo.name}}"  readOnly="true"  class="form-control"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_office" type="text" value="{{row.invoice.workInvoice.office.name}}"  readOnly="true"  class="form-control"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_client" type="text" value="{{row.invoice.workInvoice.client.name}}"  readOnly="true"  class="form-control"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_statusStr" name="settleDetailList[{{idx}}].statusStr" type="text" value="${fns:getDictLabel(row.status, 'settle_status', '未确认')}"  readOnly="true" class="form-control"/>
                                <input type="hidden" id="settleDetailList{{idx}}_status" name="settleDetailList[{{idx}}].status" type="text" value="{{row.status}}" readOnly="true" class="form-control"/>
                            </td>
                            <td>
                                <input id="settleDetailList{{idx}}_settleDate" name="settleDetailList[{{idx}}].settleDate" type="text" value="<fmt:formatDate value="${row.settleDate}" pattern="yyyy-MM-dd"/>"  readOnly="true"  class="form-control "/>
                            </td>
                            <td class="text-center op-td">
                            <span class="op-btn op-btn-delete" onclick="delRow(this, '#settleDetailList{{idx}}')" ><i class="fa fa-trash"></i> 取消</span>
                            </td>
                            </tr>//-->
                        </script>
                        <script type="text/javascript">
                            var settleDetailIdx = 0, settleDetailTpl = $("#settleDetailTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
                            var data;
                            $(document).ready(function() {
                                data = ${fns:toJson(workReceiptsSettle.settleDetailList)};
                                if(data!=null) {
                                    for (var i = 0; i < data.length; i++) {
                                        addRow('#settleDetailList', settleDetailIdx, settleDetailTpl, data[i]);
                                        $(":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, row){
                                var idx1 = $("#settleDetailList tr").length +1;
                                bornTemplete(list, idx, tpl, row, idx);
                                settleDetailIdx +=1;
                                var stausId = "#settleDetailList"+idx+"_status";
                                var status = $(stausId).val();
                                if(status==null||status==''){
                                    $(stausId).val(0);
                                }
                            }

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

                            function getAllInvoice() {
                                var invoices = $("#settleDetailList 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 setInvoiceValue(obj,idx) {
                                $.ajax({
                                    type:'post',
                                    url:'${ctx}/workinvoicedetail/workInvoiceDetail/ajaxInvoice',
                                    data:{
                                        "id":obj.id
                                    },
                                    success:function(data){
                                        if(data.success){
                                            var pref = "#settleDetailList"+idx+"_";
                                            var amtId = pref+"invoiceAmt";
                                            var taxId = pref+"taxMoney";
                                            var incomeId = pref+"incomeAmt";
                                            var project = pref+"project";
                                            var contract = pref+"contract";
                                            var office = pref+"office";
                                            var client = pref+"client";
                                            $(amtId).val(data.body.invoice.totalMoney);
                                            $(taxId).val(data.body.invoice.taxMoney);
                                            $(incomeId).val(data.body.invoice.incomeMoney);
                                            $(project).val(data.body.invoice.workInvoice.project.projectName);
                                            $(contract).val(data.body.invoice.workInvoice.project.workContractInfo.name);
                                            $(office).val(data.body.invoice.workInvoice.office.name);
                                            $(client).val(data.body.invoice.workInvoice.client.name);
                                            $(":input.money").change();
                                            caculateAmt(pref);
                                        }
                                    }
                                })
                            }

                            function caculateAmt(prefix) {
                                var settlePctId = prefix+"settlePct";
                                var settleAmtId = prefix+"settleAmt";
                                var incomeId = prefix+"incomeAmt";
                                var settlePct = $(settlePctId).val();
                                var  imcomeAmt = $(incomeId).val();
                                if(settlePct != null&&settlePct!=''&&imcomeAmt!=null&&imcomeAmt!=''){
                                    var pct = (settlePct.replace("%",""))/100;
                                    var amt = imcomeAmt.replace(/,/g,"");
                                    $(settleAmtId).val(amt*pct);
                                }else {
                                    $(settleAmtId).val(0);
                                }
                                $(settleAmtId).change();
                            }
                        </script>
                    </div>
                </div>
        </form:form>
        </div>
    </div>
</body>
</html>