<%@ 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;
        var count = 0;
        function doSubmit(obj){//回调函数，在编辑和保存动作时，供openDialog调用提交表单。
            if(validateForm.form()){
                if(obj == 2){
                    $("#flag").val("no");
                }else{
                    $("#flag").val("yes");
                }
                var m = ${workInvoiceAlter.money};
                var money = "0.00";
                //自动计算出结果并填充在相应的输入框中
                var size = $("#workAccountList tr").length+count;
                for (var i = 0;i<size;i++){
                    var _totalMoney = $("#workAccountList"+i+"_totalMoney").val();

                    var delFlag = $("#workAccountList"+i+"_delFlag").val();
                    if (_totalMoney!=undefined && isNumber(_totalMoney) && delFlag==0){
                        if(money==""){
                            money = parseFloat(_totalMoney).toFixed(2);
                        }else {
                            money = (parseFloat(money) + parseFloat(_totalMoney)).toFixed(2);
                        }
                    }
                }
                if(money != m){
                    top.layer.alert('发票明细总价税合计与主信息价税合计不等，禁止提交！', {icon: 0});
                    return;
                }
                $("#inputForm").submit();
                return true;
            }
            return false;
        }
        $(document).ready(function() {
            $("#name").focus();
            jQuery.validator.addMethod("isUscCode", function(value, element) {
                if (this.optional(element)){
                    return true;
                }
                var uscCode = /^((\w{15})|(\w{18})|(\w{20}))$/;
                return uscCode.test(value);
            }, "请填写正确的纳税人识别号");
            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);
                    }
                }
            });



            laydate.render({
                elem: '#takeDate', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
                event: 'focus', //响应事件。如果没有传入event，则按照默认的click
                type : 'date'
            });
            laydate.render({
                elem: '#invoiceDate', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
                event: 'focus', //响应事件。如果没有传入event，则按照默认的click
                type : 'date'
            });
        });

        function addRow(list, idx, tpl, row){
            var idx1 = $("#workAccountList tr").length;
            if(list == '#workAccountList' && idx1 < 100){
                bornTemplete(list, idx, tpl, row, idx1);
                if($("#invoiceType").val()=="专票"){
                    $("#workAccountList"+idx+"_code").attr("minlength","10");
                    $("#workAccountList"+idx+"_code").attr("maxlength","10");
                }else if($("#invoiceType").val()=="普票"){
                    $("#workAccountList"+idx+"_code").attr("minlength","12");
                    $("#workAccountList"+idx+"_code").attr("maxlength","12");
                }
                if(idx>0){
                    var i = idx-1;
                    var code = $("#workAccountList"+i+"_code").val();
                    if(code == null || code == undefined || code == ""){
                        i = idx-2;
                        code = $("#workAccountList"+i+"_code").val();
                        console.log(i);
                    }
                    $("#workAccountList"+idx+"_code").val(code);
                }
            }
        }
        function bornTemplete(list, idx, tpl, row, idx1){
            $(list).append(Mustache.render(tpl, {
                idx: idx, delBtn: true, row: row,
                order:idx1 + 1
            }));
            $(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) {
            count++;
            var id = $(prefix + "_id");
            var delFlag = $(prefix + "_delFlag");
            if (id.val() == "") {
                $(obj).parent().parent().remove();
            } else if (delFlag.val() == "0") {
                delFlag.val("1");
                $(obj).html("&divide;").attr("title", "撤回删除");
                $(obj).parent().parent().addClass("error");
                $(obj).parent().parent().addClass("hide");
            } else if (delFlag.val() == "1") {
                delFlag.val("0");
                $(obj).html("&times;").attr("title", "删除");
                $(obj).parent().parent().removeClass("error");
            }
            // var idx1 = $("#workAccountList tr").length; //tr 总数
            // for (var i = 0; i < idx1; i++) {
            //     $("#workAccountList tr").eq(i).find("td").eq(1).html(i + 1);
            // }
        }
        function setVs(obj){
            var a = $(obj).attr("id");
            var b = a.replace('allPrice','proportion');
            var value = obj.value;
            var p = $("#price").val() || 0;
            if(!p || p == 0){
                parent.layer.msg("请先填写造价指标,且不能为零",{icon:5});
                return;
            }
            var num = value/p ;
            if(!/^\d+(\.\d{1,2})?$/.test( value )){
                parent.layer.msg("合价必须输入数字",{icon:5});
            }else{
                $("#" +  b ).val(parseFloat(num.toFixed(2)));
            }
        }
        function isNumber(val){
            if(val === "" || val ==null){
                return false;
            }
            var regPos = /^\d+(\.\d+)?$/; //非负浮点数
            var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
            if(regPos.test(val) || regNeg.test(val)){
                return true;
            }else{
                return false;
            }

        }
        function setTaxMoney(obj){
            var a = $(obj).attr("id");
            var b = a.replace('tax','taxMoney');
            var t = a.replace('tax','totalMoney');
            var tr = a.replace('tax','taxRate');
            var value = obj.value || 0;
            if(!value){
                parent.layer.msg("请正确填写税率",{icon:5});
                $("#" +  b ).val("");
                $("#" +  tr ).val("");
                return;
            }
            var m = ${workInvoiceAlter.money};
            var t2 = $("#" +  t ).val();
            if(!/^\d+(\.\d{1,4})?$/.test( t2 )){
                parent.layer.msg("请正确填写价税合计",{icon:5});
                return;
            }else if(t2 > m) {
                $("#" +  b ).val("");
                $("#" +  tr ).val("");
                parent.layer.msg("所填值大于发票总价税合计",{icon:5});
                return;
            }
            // console.log("-value----"+value);
            var tax = 1 + value/100;
            // console.log("-tax----"+tax);
            var p = $("#" +  t ).val() || 0;//获取价税合计
            //  console.log("-----"+p);
            if(!p || p == 0){
                parent.layer.msg("请先填写价税合计,且不能为零",{icon:5});
                return;
            }
            var num = p/tax || 0;
            // console.log("-----"+num);
            $("#" +  b ).val(parseFloat(num.toFixed(2)));
            var taxRate = p - num;
            $("#" +  tr ).val(parseFloat(taxRate.toFixed(2)));
        }
        function setCheck(obj){
            var aa = $(obj).attr("id");
            var b = aa.replace('totalMoney','taxMoney');
            //console.log("b====="+b);
            var tr = aa.replace('totalMoney','taxRate');
            // console.log("tr====="+tr);
            $("#" +  b ).val("");
            $("#" +  tr ).val("");
            var m = ${workInvoiceAlter.money};
            //  console.log("-m----"+m);
            var a = obj.value;
            // console.log("-a----"+a);
            if(a > m) {
                $("#" +  b ).val("");
                $("#" +  tr ).val("");
                parent.layer.msg("所填值大于发票总价税合计",{icon:5});
                return;
            }
        }
        function getMoney(value,obj){
            var aa = $(obj).attr("id");
            var b = aa.replace('totalMoney','taxMoney');
            console.log("b====="+b);
            var tr = aa.replace('totalMoney','taxRate');
            var m = ${workInvoiceAlter.money};
            var money = "0.00";
            //自动计算出结果并填充在相应的输入框中
            var size = $("#workAccountList tr").length+count;
            for (var i = 0;i<size;i++){
                var _totalMoney = $("#workAccountList"+i+"_totalMoney").val();

                var delFlag = $("#workAccountList"+i+"_delFlag").val();
                if (_totalMoney!=undefined && isNumber(_totalMoney) && delFlag==0){
                    if(money==""){
                        money = parseFloat(_totalMoney).toFixed(2);
                    }else {
                        money = (parseFloat(money) + parseFloat(_totalMoney)).toFixed(2);
                    }
                }
            }
            if(money >m){
                console.log("money--------"+money);
                $("#" + aa ).val("");
                $("#" +  b ).val("");
                $("#" +  tr ).val("");
                parent.layer.msg("发票明细价税合计总值大于主申请发票价税合计",{icon:5});
                return;
            }
        }
        function setV(obj){
            var a =  $(obj).attr("id");
            var c = "京";
            var date=new Date;
            var year=date.getFullYear();
            var month=date.getMonth()+1;
            month =(month<10 ? "0"+month:month);
            var mydate = (year.toString()+month.toString());
            var timestamp="["+mydate+"]";//获取固定格式年月
            var number = c+timestamp;
            $("#" +  a ).val(number);
        }
        function checkSame(obj){
            var value =obj.value;
            var a = $(obj).attr("id");
            var idx = a.replace('_number','');
            var idxx = idx.replace('workAccountList','')
            //console.log(idxx);
            var b = a.replace('number','oldNumber');
            var oldValue = $("#" +  b ).val();

            var size = $("#workAccountList tr").length+count;
            for (var i = 0;i<size;i++){
                var _number = $("#workAccountList"+i+"_number").val();

                var delFlag = $("#workAccountList"+i+"_delFlag").val();
                if (_number!=undefined&& delFlag==0 && i!= idxx ){
                    if(_number == value){
                        $("#" +  a ).val("");
                        parent.layer.msg("重复的发票号，请重新输入",{icon:5});
                        return;
                    }
                }
            }
            $.ajax({
                type:'post',
                url:'${ctx}/workinvoicedetail/workInvoiceDetail/checkSame',
                data:{
                    "number":value,"oldNumber":oldValue
                },
                success:function(data){
                    //console.log("========data"+data);
                    if("false" == data){
                        $("#" +  a ).val("");
                        parent.layer.msg("重复的发票号，请重新输入",{icon:5});
                        return;
                    }
                }
            })
        }
	</script>
</head>
<body>
<div class="single-form">
	<div class="container">
		<form:form id="inputForm" modelAttribute="workInvoiceAlter" action="${ctx}/workinvoicealter/workInvoiceAlter/saveAudit" method="post" class="form-horizontal">
			<form:hidden path="id"/>
			<%--<form:hidden path="invoiceDate"/>--%>
			<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"/>
			<form:hidden path="province" id="province"/>
			<c:set var="status" value="${workInvoiceAlter.act.status}" />

			<div class="form-group layui-row first lw14">
				<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 htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.project.projectName}"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">发票申请编号：</label>
					<div class="layui-input-block">
						<div class="input-group">
							<form:input path="number" htmlEscape="false" readonly="true"   class="form-control layui-input"/>
							<span class="input-group-btn">
							<label class="form-status"><c:choose><c:when test="${ empty workInvoiceAlter.invoiceState}">新添</c:when><c:otherwise>${fns:getDictLabel(workInvoiceAlter.invoiceState, 'audit_state','')}</c:otherwise></c:choose></label>
						</span>
						</div>
					</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">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.project.workContractInfo.name}"/>
					</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">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.project.projectId}"/>
					</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">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.project.workContractInfo.client.name}"/>
					</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">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.office.name}"/>
					</div>
				</div>
			</div>
			<div class="form-group layui-row first lw14">
				<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 htmlEscape="false" readonly="true"   class="form-control layui-input" value="<c:choose><c:when test="${workInvoiceAlter.ext eq '0'}">本公司开票	</c:when><c:when test="${workInvoiceAlter.ext eq '1'}">上级公司开票</c:when></c:choose>"/>
					</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">
						<input htmlEscape="false" readonly="true" id="invoiceType"  class="form-control layui-input" value="<c:choose><c:when test="${workInvoiceAlter.invoiceType eq '1'}">专票</c:when><c:when test="${workInvoiceAlter.invoiceType eq '2'}">普票</c:when></c:choose>"/>
					</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">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.client.name}"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">纳税人识别号：</label>
					<div class="layui-input-block">
						<input htmlEscape="false" readonly="true"   class="form-control isUscCode layui-input" value="${workInvoiceAlter.orUnicode}"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">地址：</label>
					<div class="layui-input-block">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.address}"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">电话：</label>
					<div class="layui-input-block">
						<input htmlEscape="false" readonly="true"   class="form-control layui-input" value="${workInvoiceAlter.telephone}"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">开户银行：</label>
					<div class="layui-input-block">
						<form:input id ="bank" readonly="true"  path="bank" htmlEscape="false"   class="form-control layui-input"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">银行账号：</label>
					<div class="layui-input-block">
						<form:input id="bankNumber" readonly="true"  path="bankNumber" htmlEscape="false"   class="form-control layui-input"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm12">
					<label class="layui-form-label"><span class="require-item">*</span>价税合计(元)：</label>
					<div class="layui-input-block">
						<form:input id=""  path="money" readonly="true"  htmlEscape="false" class="form-control number required layui-input"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm12 with-textarea">
					<label class="layui-form-label"><span class="require-item">*</span>开票内容要求：</label>
					<div class="layui-input-block">
						<form:textarea path="content" readonly="true" id="contractTypeDoc" htmlEscape="false" rows="4"    class="form-control required"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">开票人：</label>
					<div class="layui-input-block">
						<form:input id=""  path="drawerName" htmlEscape="false" readonly="true"  class="form-control layui-input"/>
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">开票时间：</label>
					<div class="layui-input-block">
						<input class="form-control layer-date laydate-icon layui-input laydate-icondate" id="invoiceDate" readonly="true"  name="invoiceDate" value="<fmt:formatDate
							value="${workInvoiceAlter.invoiceDate}" pattern="yyyy-MM-dd"/>">
					</div>
				</div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label">领票时间：</label>
					<div class="layui-input-block">
						<input class="form-control layer-date laydate-icon layui-input laydate-icondate" id="takeDate" readonly="true"  name="takeDate" value="<fmt:formatDate
							value="${workInvoiceAlter.takeDate}" pattern="yyyy-MM-dd"/>">
					</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('#workAccountList', workAccountListRowIdx, workAccountListTpl);workAccountListRowIdx = workAccountListRowIdx + 1;" title="新增"><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 can-edit no-bottom-margin">
						<thead>
						<tr>
							<th><span class="require-item">*</span>发票代码</th>
							<th><span class="require-item">*</span>发票号</th>
							<th width="100px"><span class="require-item">*</span>价税合计</th>
							<th width="80px"><span class="require-item">*</span>税率</th>
							<th width="100px"><span class="require-item">*</span>金额</th>
							<th width="100px"><span class="require-item">*</span>税额</th>
							<th width="100px"><span class="require-item">*</span>累计登记金额</th>
							<th width="80px">操作</th>
								<%--<th><span class="require-item">*</span>发票状态</th>&lt;%&ndash;正常&ndash;%&gt;--%>
								<%--<th><span class="require-item">*</span>被退标记</th>--%>
								<%--<th><span class="require-item">*</span>被退票号</th>--%>
								<%--<th><span class="require-item">*</span>开票日期</th>--%>
						</tr>
						</thead>
						<tbody id="workAccountList">
						</tbody>
					</table>

					<script type="text/template" id="workAccountListTpl">//<!--
                                    <tr id="workAccountList{{idx}}">
                                        <td class="hide">
                                            <input id="workAccountList{{idx}}_id" name="workAccountList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
                                            <input id="workAccountList{{idx}}_delFlag" name="workAccountList[{{idx}}].delFlag" type="hidden" value="0"/>
                                        </td>
                                    	<td>
                                        	<input id="workAccountList{{idx}}_code" name="workAccountList[{{idx}}].code" type="text" value="{{row.code}}"  minlength="10" maxlength="12"  class="form-control number required"/>
                                   		 </td>
                                    	 <td>
                                        	<input id="workAccountList{{idx}}_number" name="workAccountList[{{idx}}].number" onchange="checkSame(this)" type="text" value="{{row.number}}"  minlength="8" maxlength="8"  class="form-control number required"/>
									 		<input type="hidden" id="workAccountList{{idx}}_oldNumber" value="{{row.number}}"/>
                                   		 </td>
                                    	<td>
                                            <input id="workAccountList{{idx}}_totalMoney"  onblur="setCheck(this)" onchange="getMoney(this.value,this)" name="workAccountList[{{idx}}].totalMoney" type="text" value="{{row.totalMoney}}"    class="form-control number required"/>
                                        </td>
                                        <td>
                                        <div class="input-group">
                                            <input id="workAccountList{{idx}}_tax" onblur="setTaxMoney(this)" name="workAccountList[{{idx}}].tax" type="text" value="{{row.tax}}"    class="form-control number required"/><span class="input-group-addon input-height">%</span>
                                            </div>

                                        </td>
                                        <td>
                                            <input id="workAccountList{{idx}}_taxMoney" name="workAccountList[{{idx}}].taxMoney" type="text" value="{{row.taxMoney}}"    class="form-control number required"/>
                                        </td>
										<td>
                                            <input id="workAccountList{{idx}}_taxRate" name="workAccountList[{{idx}}].taxRate" type="text" value="{{row.taxRate}}"    class="form-control number required"/>
                                        </td>
                                        <td>
                                            <input id="workAccountList{{idx}}_incomeMoney" name="workAccountList[{{idx}}].incomeMoney" type="text" value="0"  readonly="true"  class="form-control required"/>
                                        </td>

                                            <input id="workAccountList{{idx}}_state" name="workAccountList[{{idx}}].state"  type="hidden" value="正常"   class="form-control"/>

                                            <input id="workAccountList{{idx}}_backSign" name="workAccountList[{{idx}}].backSign"  type="hidden" value="正常"  readonly="true"  class="form-control required"/>

                                            <input id="workAccountList{{idx}}_backNumber" name="workAccountList[{{idx}}].backNumber"  type="hidden" value=""  readonly="true"  class="form-control required"/>


                                        <td class="text-center op-td">
                                            {{#delBtn}}<span class="op-btn op-btn-delete" onclick="delRow(this, '#workAccountList{{idx}}')" title="删除"><i class="glyphicon glyphicon-remove"></i>&nbsp;删除</span>{{/delBtn}}
                                        </td>
                                    </tr>//-->
					</script>
					<script type="text/javascript">
                        var workAccountListRowIdx = 0, workAccountListTpl = $("#workAccountListTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
                        $(document).ready(function() {
                            var data = ${fns:toJson(workInvoiceAlter.workAccountList)};
                            for (var i=0; i<data.length; i++){
                                addRow('#workAccountList', workAccountListRowIdx, workAccountListTpl, data[i]);
                                if($("#invoiceType").val()=="专票"){
                                    $("#workAccountList"+workAccountListRowIdx+"_code").attr("minlength","10");
                                    $("#workAccountList"+workAccountListRowIdx+"_code").attr("maxlength","10");
                                }else if($("#invoiceType").val()=="普票"){
                                    $("#workAccountList"+workAccountListRowIdx+"_code").attr("minlength","12");
                                    $("#workAccountList"+workAccountListRowIdx+"_code").attr("maxlength","12");
                                }
                                workAccountListRowIdx = workAccountListRowIdx + 1;
                            }
                        });
					</script>

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