<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE HTML>
<html>
<head>
    <meta name="decorator" content="base"/>
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/static/css/reset.css">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/dist/viewer.css" media="all">
    <style>
        html {background-color: #fff;padding-bottom: 50px;}td, th {text-align: center !important;}
        .layui-btn-danger {
            background-color: #0a6597;
        }
        .layui-tab{position: relative}
        a.gl-btn{position: absolute; top: 10px; right: 20px; background: #0a6597; padding: 0 10px; color: #FFF;}
        .layui-card{margin-bottom: 0px}
        .layui-form-select dl{max-height: 230px}
    </style>
</head>

<body>
<div class="layui-form">
    <div class="layui-card-body layui-col-xs12" id="LAY_app">
        <blockquote class="layui-elem-quote">订单信息</blockquote>
        <div class="layui-card">
            <div class="layui-card-body">
                <div class="layui-row layui-col-space12 layui-form-item">
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>下单类型：</label>
                        <div class="layui-input-block">
                            <select id="type" name="type" lay-verify="required" lay-filter="orderType">
                                <option value="">请选择</option>
                                <option value="2" selected>物料储备</option>
<%--                                <option value="1">电站下单</option>--%>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>企企项目：</label>
                        <div class="layui-input-block">
                            <select id="qqProjectCode" name="qqProjectCode" lay-verify="required" lay-filter="qqProjectCode">
                                <c:forEach items="${qqProjectList}" var="qqProject">
                                    <option value="${qqProject.columns.code}" ${qqProjectList.size() == 1 ? 'selected': ''}>${qqProject.columns.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>入库仓库：</label>
                        <div class="layui-input-block">
                            <select name="inWarehouseId" lay-verify="required" lay-filter="inWarehouseId">
                                <option value="">请选择</option>
                                <c:forEach items="${wares}" var="warehouse">
                                    <option value="${warehouse.columns.id}"
                                        ${wares.size() == 1 ? 'selected': ''}>${warehouse.columns.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>接货人：</label>
                        <div class="layui-input-block">
                            <input type="text" autocomplete="off" name="personInCharge" id="person_in_charge" class="layui-input layui-bg-gray"<c:if test="${userId ne '2c9080787e4882f3017e4c67e9f542e1'}">readonly</c:if>  value="${rd.columns.person_in_charge}">
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>联系方式：</label>
                        <div class="layui-input-block">
                            <input type="text" autocomplete="off" id="mobile" name="mobile" class="layui-input layui-bg-gray" value="${rd.columns.mobile}" readonly>
                        </div>
                    </div>

                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>省：</label>
                        <div class="layui-input-block">
                            <input name="province" id="province" value="${rd.columns.province}" readonly class="layui-input layui-bg-gray" >
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>市：</label>
                        <div class="layui-input-block">
                            <input name="city" id="city" value="${rd.columns.city}" readonly class="layui-input layui-bg-gray" >
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label w-130"><i class="red">*</i>区县：</label>
                        <div class="layui-input-block">
                            <input name="area" id="area" value="${rd.columns.area}" readonly class="layui-input layui-bg-gray" >
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md8 layui-col-sm8">
                        <label class="layui-form-label w-130">仓库地址：</label>
                        <div class="layui-input-block ">
                            <input type="text" autocomplete="off" id="address" name="address" class="layui-input layui-bg-gray" value="${rd.columns.address}" readonly>
                        </div>
                    </div>


                    <div class="layui-col-xs12 mb-10 pr-30">
                        <div class="layui-form-item">
                            <label class="layui-form-label w-130">订单备注：</label>
                            <div class="layui-input-block ">
                                <textarea name="remark" class="layui-textarea" style="min-height: 60px"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-inline layui-col-xs12">
                            <label class="layui-form-label w-120"><i class="mark">*</i>施工人员保单：</label>
                            <div class="layui-input-block img-box ml-120">
                                <div style="display: flex">
                                    <div id="insuranceFilesDiv">
                                        <div  id="insuranceFilesUploader">
                                            <span style="color:blue;cursor: pointer" id="insuranceFiles">上传</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <%--
                    <div class="layui-row">
                        <div class="layui-inline layui-col-xs12">
                            <label class="layui-form-label"><i class="mark">*</i>安全教育登记表：</label>
                            <div class="layui-input-block img-box ml-120">
                                <div style="display: flex">
                                    <div id="safetyFilesDiv">
                                        <div  id="safetyFilesUploader">
                                            <span style="color:blue;cursor: pointer" id="safetyFiles">上传</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    --%>
                </div>
            </div>
        </div>
        <div class="layui-card zizhuOrder">
            <blockquote class="layui-elem-quote">标准物料</blockquote>
            <div class="layui-card-body ">
                <div class="layui-row layui-col-space12 layui-form-item">
                    <div class="layui-col-xs12 mb-10 pr-30 pl-30">

                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th style="width: 5%">序号</th>
                                <th style="width: 20%">物料类型</th>
                                <th>物料规格</th>
                                <th>零售价</th>
                                <th style="width: 15%">申请数量</th>
                                <th style="width: 20%">操作</th>
                            </tr>
                            </thead>
                            <tbody id="materialBody">
                            <tr class="materialtr">
                                <td>1</td>
                                <td >
                                    <select class="materialType" name="materialType" lay-filter="materialType">
                                        <option value="">请选择</option>
                                        <c:forEach var="type" items="${typeList}">
                                            <option value="${type.columns.id}">${type.columns.name}</option>
                                        </c:forEach>

                                        <%--<option value="2">并网箱</option>
                                        <option value="3">组件</option>
                                        <option value="4">支架</option>--%>
                                    </select>
                                </td>
                                <td>
                                    <select class="materialSpecs" name="materialSpecs"  lay-filter="materialSpecs">
                                    </select>
                                </td>
                                <td class="salesPrice"></td>
                                <td><input type="text" class="layui-input" name="amount" onkeyup="inputAmount()"/><input type="hidden" class="materialPrice"/></td>
                                <td>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger addDaili" onclick="addtr(this)">添加</button>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger deleteBut layui-hide" onclick="delete1(this)">删除</button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <table class="layui-table totalTable hide">
                            <tbody>
                            <tr>
                                <td colspan="3"></td>
                                <td style="width: 15%" class="totalAmountHtml"></td>
                                <td style="width: 20%"><input type="hidden" class="totalAmount" value=""/></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card entryOrder hide">
            <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                <ul class="layui-tab-title" id="changeTabId" lay-filter="changeTab" >
                    <li class="layui-this">电站信息</li>
                    <li>物料信息</li>
                </ul>
                <a href="#" class="gl-btn customerEntey">选择电站</a>
            </div>
            <div class="layui-card-body customerEntrys">
                <div class="layui-row layui-col-space12 layui-form-item">
                    <div class="layui-col-xs12 mb-10 pr-30 pl-30">
                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th style="width: 5%">序号</th>
                                <th style="width: 12%">电站编码</th>
                                <th style="width: 15%">客户姓名</th>
                                <th >安装地址</th>
                                <th style="width: 15%">设计容量（W）</th>
                                <th style="width: 15%">登记时间</th>
                                <th style="width: 10%">操作</th>
                            </tr>
                            </thead>
                            <tbody id="entryListBody">

                            </tbody>
                        </table>

                    </div>
                </div>
            </div>
            <div class="layui-card-body entryMates hide">
                <div class="layui-row layui-col-space12 layui-form-item">
                    <div class="layui-col-xs12 mb-10 pr-30 pl-30">
                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th style="width: 5%">序号</th>
                                <th style="width: 20%">物料类型</th>
                                <th>物料规格</th>
                                <th>零售价</th>
                                <th style="width: 15%">申请数量</th>
                                <th style="width: 20%">操作</th>
                            </tr>
                            </thead>
                            <tbody id="entryMaterialBody">

                            </tbody>
                        </table>
                        <table class="layui-table totalTable hide">
                            <tbody>
                            <tr>
                                <td colspan="3"></td>
                                <td style="width: 15%" class="totalAmountHtml"></td>
                                <td style="width: 20%"><input type="hidden" class="totalAmount" value=""/></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

      <%--  <div class="layui-card">
            <blockquote class="layui-elem-quote">非标准物料</blockquote>
            <div class="layui-card-body ">
                <div class="layui-col-xs12 mb-10 pr-30">
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <label class="layui-form-label">代码：</label>
                        <div class="layui-input-block">
                            <div id="code"></div>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md3 layui-col-sm3">
                        <input type="button" class="layui-btn layui-btn-sm ml-10 mt-5" id="importPlan" value="批量导入"/>
                    </div>
                </div>
                <div class="layui-row layui-col-space12 layui-form-item">
                    <div class="layui-col-xs12 mb-10 pr-30 pl-30">

                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th>序号</th>
                                <th>物料代码</th>
                                <th>物料名称</th>
                                <th>物料类型</th>
                                <th>物料品牌</th>
                                <th>物料规格</th>
                                <th>申请数量</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="optionalMaterialBody">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>--%>
            <input type="hidden" id="entryIds" name="entryIds">
        <div class="layui-form-item operate-footer" style="text-align: center;">
            <input type="button" onclick="budget();" id="budget" class="layui-btn " value="授信余额预算">
            <input type="button" lay-submit lay-filter="templeSave" id="templeSave" class="layui-btn" value="暂存">
            <input type="button" lay-submit lay-filter="save" id="save" class="layui-btn layui-btn-disabled" disabled value="提交">

         <%--   <input type="button"   value="取消" class="layui-btn layui-btn-primary " onclick="closeDiv();" >--%>
        </div>

    </div>
    <%--<div class="mt-10 layui-col-sm1 text-c">
        <input type="button" lay-submit lay-filter="save" id="save" class="layui-btn " value="保存">
    </div>--%>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script src="${ctxPlugin}/lib/xm-select.js"></script>
<script src="${ctxPlugin}/lib/base64.js"></script>
<script type="text/javascript">
    //初始数据
    var $form;
    var form;
    var $;
    var imgs = '';
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    var matypeList ;
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['form', 'layedit', 'laydate', 'jquery', 'upload','layer'], function () {
        $ = layui.jquery;
        form = layui.form;
        $form = $('form');
        var upload = layui.upload;

        upload.render({
            elem: '#insuranceFilesUploader',
            url: '${ctx}/common/uploadFile3',
            accept: 'file',
            exts: 'pdf|doc',
            before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                });
            },
            done: function (res) {
                //上传完毕回调
                let path = res.path;
                let index = path.lastIndexOf('/');
                let name = path.substring(index + 1);
                let imgCount = $("#insuranceFilesDiv").find(".insuranceFiles").length;
                if ((imgCount + 1) >= 5) {
                    $("#insuranceFilesUploader").hide();
                }
                let html = '<div style="margin-top: 5px"><span style="color:red;" class="layui-icon-close layui-icon" onclick="delImg(this,\'insuranceFilesUploader\')"></span>';
                html += '<a style="color:#2890ac;" target="_blank"  onclick="previewUrl(' + "\'" + '${commonStaticImgPath}' + path + "\'" + ')"    class="download-link">' + name + '</a>';
                html += '<input type="hidden" class="insuranceFiles" value="' + path + '"/> </div>';
                $("#insuranceFilesDiv").append(html);
            },
            error: function () {
                //请求异常回调
            }
        });

        upload.render({
            elem: '#safetyFilesUploader',
            url: '${ctx}/common/uploadFile3',
            accept: 'file',
            exts: 'pdf|doc',
            before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                });
            },
            done: function (res) {
                //上传完毕回调
                let path = res.path;
                let index = path.lastIndexOf('/');
                let name = path.substring(index + 1);
                let imgCount = $("#safetyFilesDiv").find(".safetyFiles").length;
                if ((imgCount + 1) >= 5) {
                    $("#safetyFilesUploader").hide();
                }
                let html = '<div style="margin-top: 5px"><span style="color:red;" class="layui-icon-close layui-icon" onclick="delImg(this,\'safetyFilesUploader\')"></span>';
                html += '<a style="color:#2890ac;" target="_blank"  onclick="previewUrl(' + "\'" + '${commonStaticImgPath}' + path + "\'" + ')"    class="download-link">' + name + '</a>';
                html += '<input type="hidden" class="safetyFiles" value="' + path + '"/> </div>';
                $("#safetyFilesDiv").append(html);
            },
            error: function () {
                //请求异常回调
            }
        });
       /* var codeXm = xmSelect.render({
            el: '#code',
            name: 'code',
            radio: true,
            tips: '请输入查询',
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (val, cb, show) {
                searchVal(val, cb, {
                    code: val,
                    attribute: '1'
                }, 'code');
            },
            on: function (data) {
                if (data.isAdd && data.arr.length > 0) {
                    appendTr(data);
                }
            }
        });*/

        function appendTr(data) {
            var d = data.arr[0].origin;
            var html = '<tr>'
                + '<td data-id="' + d.id + '" ></td>'
                + '<td>' + d.code + '</td>'
                + '<td>' + d.material_name + '</td>'
                + '<td>' + d.material_type + '</td>'
                + '<td>' + d.material_brand + '</td>'
                + '<td>' + d.material_specs + '</td>'
                + '<td><input type="text" class="layui-input" name="amount" lay-verify="required" /></td>'
                + '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>'
                + '</tr>';

            var $trs ;
            if(d.type =='1'){
                //自选物料
                $trs = $('#optionalMaterialBody>tr');
            } else {
                return;
            }
            var exist = false;
            for (var i = 0; i < $trs.length; i++) {
                var $tr = $trs.eq(i);
                var id = $tr.find('td:first').data('id');
                if (id === d.id) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                if(d.type =='1'){
                    $('#optionalMaterialBody').append(html);
                    appendOpSort();
                }
            } else {
                layer.msg('物料已存在');
            }
            data.arr.length = 0;
            codeXm.reset();
            // descXm.reset();
        }

        window.del = function(obj){
            $(obj).closest('tr').remove();
        }

        $('#importPlan').click(function(){

            layer.open({
                title: '导入物料',
                type: 2,
                area: ['550px', '300px'],
                content: '${ctx}/material/apply/ImportMaterialForm'
            });
        });
        $('.customerEntey').click(function(){
            var entryIds="";
            $("#entryListBody tr").each(function (index) {
                $(this).find(".idx").text(index + 1);
                if(isBlank(entryIds)){
                    entryIds =$(this).attr("data-entryId");
                }else{
                    entryIds = entryIds+","+$(this).attr("data-entryId");
                }
            })
            layer.open({
                title: '选择电站',
                type: 2,
                area: ['70%', '70%'],
                content: '${ctx}/material/apply/findCustomerEntryList?entryIds='+entryIds
            });
        });



      /*  window.importMaterialApply = function(data){

            var html = "";
            var zizhuhtml ="";
            var ziin=1;
            var inva=1;
            for(var i=0; i<data.materialList.length; i++){
                var d = data.materialList[i];
                if(d.materialAttribute=='1'){
                    zizhuhtml += '<tr>'
                        + '<td data-id="' + d.materialId + '" >' + ziin + '</td>'
                        + '<td>' + d.code + '</td>'
                        + '<td>' + d.name + '</td>'
                        + '<td>' + d.type + '</td>'
                        + '<td>' + d.materialBrand + '</td>'
                        + '<td>' + d.materialSpecs + '</td>'
                        + '<td><input type="text" class="layui-input" name="amount" lay-verify="required" value="'+d.amount+'"/></td>'
                        + '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>'
                        + '</tr>';
                    ziin ++;
                }

            }

            $('#optionalMaterialBody').empty().append(zizhuhtml);
        };*/

        function searchVal(val, cb, searchData, filed) {
            if (!isBlank(val)) {
                $.ajax({
                    type: 'post',
                    url: '${ctx}/material/apply/findCanApplyMaterials',
                    data: searchData,
                    async: false,
                    dataType: 'json',
                    success: function (d) {
                        var arr = [];
                        for (var i = 0; i < d.length; i++) {
                            var data = {};
                            data.name = d[i][filed];
                            data.value = d[i].id;
                            data.origin = d[i];
                            arr.push(data);
                        }
                        cb(arr);
                    }
                });
            } else {
                cb([]);
            }
        }

        function appendOpSort() {
            $('#optionalMaterialBody>tr').each(function (i) {
                $(this).find('td:first').html(i + 1);
            });
        }

        $("#changeTabId li").on("click",function(){
            $("#changeTabId li").removeClass("layui-this");
            $(this).addClass("layui-this");
            console.log($(this).index())
            if($(this).index() ==1 ) {
                $(".entryMates").removeClass("hide");
                $(".customerEntrys").addClass("hide");
                $(".customerEntey").hide();
            }else{
                $(".customerEntrys").removeClass("hide");
                $(".entryMates").addClass("hide");
                $(".customerEntey").show();
            }
        })

        form.on('select(inWarehouseId)',function(data){
            var value = $(data.elem).find("option:selected").val();
            if(isBlank(value)){
                return
            }
            var that_ = $(this);

            $.ajax({
                url:"${ctx}/material/apply/findWarehouseById",
                type:"POST",
                data:{
                    id:value
                }
                ,success:function (result) {

                    if(result.code =="200"){
                        var _data = result.data;
                        $("#person_in_charge").val(_data.personInCharge);
                        $("#mobile").val(_data.mobile);
                        $("#province").val(_data.province);
                        provinceOrder(_data.province,_data.city);
                        /*   $("#city").val(_data.city);
                           $("#area").val(_data.area);*/
                        cityOrder(_data.city,_data.area);
                        $("#address").val(_data.address);
                    }
                }
            })

        })
        form.on('select(qqProjectCode)',function(data){
            var orderType = $("#type").find("option:selected").val();
            if(isBlank(orderType)){
                return
            }
            if("1"== orderType){
                $(".entryOrder").removeClass("hide");
                $(".zizhuOrder").addClass("hide");
                $("#materialBody").empty();
            }else{
                $(".zizhuOrder").removeClass("hide");
                $(".entryOrder").addClass("hide");
                $(".totalTable").addClass("hide");
                $("#entryListBody").empty();
                var htm=`<tr class="materialtr">
                                <td>1</td>
                                <td >
                                    <select class="materialType" name="materialType" lay-filter="materialType">
                                        <option value="">请选择</option>
                                        <c:forEach var="type" items="${typeList}">
                                            <option value="${type.columns.id}">${type.columns.name}</option>
                                        </c:forEach>
                                    </select>
                                </td>
                                <td>
                                    <select class="materialSpecs" name="materialSpecs"  lay-filter="materialSpecs">
                                    </select>
                                </td>
                                <td class="salesPrice"></td>
                                <td><input type="text" class="layui-input" name="amount" onkeyup="inputAmount()"/><input type="hidden" class="materialPrice"/></td>
                                <td>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger addDaili" onclick="addtr(this)">添加</button>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger deleteBut layui-hide" onclick="delete1(this)">删除</button>
                                </td>
                            </tr>`;

                $("#materialBody").html(htm);
                $("#entryMaterialBody").empty();
                form.render('select');
            }



            $(".totalAmountHtml").html('')
            $(".totalAmount").val('')
        });

        form.on('select(orderType)',function(data){
            var value = $(data.elem).find("option:selected").val();
            if(isBlank(value)){
                return
            }
            if("1"== value){
                $(".entryOrder").removeClass("hide");
                $(".zizhuOrder").addClass("hide");
                $("#materialBody").empty();
            }else{
                $(".zizhuOrder").removeClass("hide");
                $(".entryOrder").addClass("hide");
                $("#entryListBody").empty();
                var htm=`<tr class="materialtr">
                                <td>1</td>
                                <td >
                                    <select class="materialType" name="materialType" lay-filter="materialType">
                                        <option value="">请选择</option>
                                        <c:forEach var="type" items="${typeList}">
                                            <option value="${type.columns.id}">${type.columns.name}</option>
                                        </c:forEach>
                                    </select>
                                </td>
                                <td>
                                    <select class="materialSpecs" name="materialSpecs"  lay-filter="materialSpecs">
                                    </select>
                                </td>
                                <td class="salesPrice"></td>
                                <td><input type="text" class="layui-input" name="amount" onkeyup="inputAmount()"/><input type="hidden" class="materialPrice"/></td>
                                <td>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger addDaili" onclick="addtr(this)">添加</button>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger deleteBut layui-hide" onclick="delete1(this)">删除</button>
                                </td>
                            </tr>`;
                                    console.log(htm);
                $("#materialBody").html(htm);
                $("#entryMaterialBody").empty();
                form.render('select');
            }
            $(".totalAmountHtml").html('')
            $(".totalAmount").val('')

        })

var cheSavw = false;
        form.on('submit(save)', function (data) {
            if(cheSavw){
                return;
            }
            var $trs = $('#materialBody>tr');
            var $trszi = $('#entryMaterialBody>tr');

            if ($trs.length === 0 && $trszi.length === 0) {
                layer.msg('请添加物料');
                return;
            }
            var arr = [];
            var type =data.field.type;
            var flag = false;
            var num = 0;
            let insuranceFiles = "";
            var chageFlag=false;
            $(".insuranceFiles").each(function () {
                if (isBlank(insuranceFiles)) {
                    insuranceFiles = $(this).val();
                } else {
                    insuranceFiles = insuranceFiles + "," + $(this).val();
                }
            });
            if (isBlank(insuranceFiles)) {
                layer.msg('请上传施工人员保单', {icon: 2});
                return;
            }

            let safetyFiles = "";
            $(".safetyFiles").each(function () {
                if (isBlank(safetyFiles)) {
                    safetyFiles = $(this).val();
                } else {
                    safetyFiles = safetyFiles + "," + $(this).val();
                }
            });
            // if (isBlank(safetyFiles)) {
            //     layer.msg('请上传安全教育登记表', {icon: 2});
            //     return;
            // }
            if("1"==type){
                //电站物料

                $("#entryMaterialBody tr").each(function (index) {
                    var obj = {};
                    var $tr = $(this);
                    var materialType = $tr.attr("data-typeId");
                    if (isBlank(materialType)) {
                        return;
                    }
                    obj.materialType = materialType;
                    var materialSpecs = $tr.find('.materialSpecs').text();
                    var price = $tr.find('.materialPrice').val();
                    if (isBlank(materialSpecs)) {
                        return;
                    }
                    if (price == 0){
                        num = index+1;
                        flag = true;
                        return;
                    }
                    obj.materialSpecs = materialSpecs;
                    obj.amount = $tr.find('input[name=amount]').val();
                    if (isBlank(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量为空');
                        return;
                    }
                    if (!/^\d+(\.\d{1,2})?$/.test(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量格式不正确');
                        return;
                    }
                    arr.push(obj);

                })
            }else{//物料储备
                $("#materialBody tr").each(function (index) {
                    var obj = {};
                    var $tr = $(this);
                    var materialType = $tr.find('select[name=materialType]').find('option:selected').text();
                    if (isBlank(materialType)) {
                        return;
                    }
                    var materialSpecs = $tr.find('select[name=materialSpecs]').val();

                    if (isBlank(materialSpecs)) {
                        return;
                    }
                    obj.materialType = materialType;
                    obj.materialSpecs = materialSpecs
                    obj.amount = $tr.find('input[name=amount]').val();
                    var price = $tr.find('.materialPrice').val();
                    if (price == 0){
                        num = index+1;
                        flag = true;
                        return;
                    }
                    if (isBlank(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量为空');
                        chageFlag=true;
                        return;
                    }
                    if (!/^\d+(\.\d{1,2})?$/.test(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量格式不正确');
                        chageFlag=true;
                        return;
                    }
                    arr.push(obj);
                })
            }
            if (chageFlag){
                return;
            }
            cheSavw = true;
            if (flag){
                layer.msg('第' +num+ '行物料暂未维护价格');
                cheSavw= false;
                return;
            }
            if (arr.length < 1) {
                layer.msg('请添加物料');
                cheSavw= false;
                return;
            }
            var inWarehouseId = data.field.inWarehouseId;
            var qqProjectCode = $("#qqProjectCode").find("option:selected").val();
            $.ajax({
                url: '${ctx}/material/order/saveApplyOrder',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify({
                    id: '${id}',
                    type: data.field.type,
                    inWarehouseId: inWarehouseId,
                    province: data.field.province,
                    city: data.field.city,
                    area: data.field.area,
                    address: data.field.address,
                    remark: data.field.remark,
                    personInCharge:data.field.personInCharge,
                    mobile:data.field.mobile,
                    entryIds:data.field.entryIds,
                    details: arr,
                    insuranceFiles:insuranceFiles,
                    safetyFiles:safetyFiles,
                    qqProjectCode:qqProjectCode
                }),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code === "200") {
                        layer.msg("保存成功", {time: 1000}, function(){
                            parent.location.reload(true);
                        });
                    } else if (res.code === '501') {
                        layer.msg(res.errMsg);
                    } else {
                        layer.msg("保存失败", {time: 1000});
                    }
                },
                error: function (data) {
                }
            });
        });

        var tepChec = false;
        form.on('submit(templeSave)', function (data) {
            if(tepChec){
                return;
            }
            var $trs = $('#materialBody>tr');

            var $trszi = $('#entryMaterialBody>tr');
            if ($trs.length === 0 && $trszi.length === 0) {
                layer.msg('请添加物料');
                return;
            }
            var arr = [];
            var type =data.field.type;
            var flag = false;
            var num = 0;
            var chageFlag=false;

            let insuranceFiles = "";
            $(".insuranceFiles").each(function () {
                if (isBlank(insuranceFiles)) {
                    insuranceFiles = $(this).val();
                } else {
                    insuranceFiles = insuranceFiles + "," + $(this).val();
                }
            });
            let safetyFiles = "";
            $(".safetyFiles").each(function () {
                if (isBlank(safetyFiles)) {
                    safetyFiles = $(this).val();
                } else {
                    safetyFiles = safetyFiles + "," + $(this).val();
                }
            });
            if("1"==type){
                //电站物料

                $("#entryMaterialBody tr").each(function (index) {
                    var obj = {};
                    var $tr = $(this);
                    var materialType = $tr.attr("data-typeId");
                    if (isBlank(materialType)) {
                        return;
                    }
                    obj.materialType = materialType;
                    var materialSpecs = $tr.find('.materialSpecs').text();
                    var price = $tr.find('.materialPrice').val();
                    if (isBlank(materialSpecs)) {
                        return;
                    }
                    if (price == 0){
                        num = index+1;
                        flag = true;
                        return;
                    }
                    obj.materialSpecs = materialSpecs;
                    obj.amount = $tr.find('input[name=amount]').val();
                    if (isBlank(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量为空');
                        chageFlag=true;
                        return;
                    }
                    if (!/^\d+(\.\d{1,2})?$/.test(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量格式不正确');
                        chageFlag=true;
                        return;
                    }
                    arr.push(obj);
                    console.log(obj)
                })
            }else{//物料储备
                $("#materialBody tr").each(function (index) {
                    var obj = {};
                    var $tr = $(this);
                    var materialType = $tr.find('select[name=materialType]').find('option:selected').text();
                    if (isBlank(materialType)) {
                        return;
                    }
                    var materialSpecs = $tr.find('select[name=materialSpecs]').val();

                    if (isBlank(materialSpecs)) {
                        return;
                    }
                    obj.materialType = materialType;
                    obj.materialSpecs = materialSpecs
                    obj.amount = $tr.find('input[name=amount]').val();
                    var price = $tr.find('.materialPrice').val();
                    if (price == 0){
                        num = index+1;
                        flag = true;
                        return;
                    }
                    if (isBlank(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量为空');
                        chageFlag=true;
                        return;
                    }
                    if (!/^\d+(\.\d{1,2})?$/.test(obj.amount)) {
                        layer.msg('第' + (index + 1) + '行申请数量格式不正确');
                        chageFlag=true;
                        return;
                    }
                    arr.push(obj);
                })
            }

            if(chageFlag){
                return;
            }
            if (flag){
                layer.msg('第' +num+ '行物料暂未维护价格');
                tepChec= false;
                return;
            }
            if (arr.length < 1) {
                layer.msg('请添加物料');
                tepChec = false;
                return;
            }
            tepChec = true;
            var inWarehouseId = data.field.inWarehouseId;
            var qqProjectCode = $("#qqProjectCode").find("option:selected").val();
            $.ajax({
                url: '${ctx}/material/order/saveApplyOrder',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify({
                    id: '${id}',
                    actionType:1,
                    type: data.field.type,
                    inWarehouseId: inWarehouseId,
                    province: data.field.province,
                    city: data.field.city,
                    area: data.field.area,
                    address: data.field.address,
                    remark: data.field.remark,
                    personInCharge:data.field.personInCharge,
                    mobile:data.field.mobile,
                    entryIds:data.field.entryIds,
                    details: arr,
                    insuranceFiles:insuranceFiles,
                    safetyFiles:safetyFiles,
                    qqProjectCode:qqProjectCode
                }),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code === "200") {
                        layer.msg("保存成功", {time: 1000}, function(){
                            parent.location.reload(true);
                        });
                    } else if (res.code === '501') {
                        layer.msg(res.errMsg);
                        tepChec = false;
                    } else {
                        layer.msg("保存失败", {time: 1000});
                    }
                },
                error: function (data) {
                }
            });
        });


        form.on('select(province)', function(data){
            var province = $(data.elem).find("option:selected").val();
            provinceOrder(province);
        });
        form.on('select(city)', function(data){
            var city = $(data.elem).find("option:selected").val();
            cityOrder(city);

        });

        form.on('select(materialType)', function (data) {
            var type = $(data.elem).val();
           // if (isBlank(type)) {
                $(this).parents(".materialtr").find('.materialSpecs').val('');
                $(this).parents(".materialtr").find('input[name=amount]').val('');

            var that_ = $(this);
            $.ajax({
                type:"POST",
                url:'${ctx}/material/apply/findElectricMaterialDate',
                data:{
                    type:type
                },
                success:function(result){
                    var html ="<option value=''>请选择</option>";
                    for(var i=0;i<result.length;i++){
                        var specs = result[i];
                        if (type == '3') {
                            html += '<option value="'+specs+'" >'+specs+'Wp</option>';
                        } else {
                            html += '<option value="'+specs+'" >'+specs+'</option>';
                        }
                    }
                    that_.parents(".materialtr").find('.materialSpecs').empty().append(html);
                    form.render('select');
                }
            });

        })

        form.on('select(materialSpecs)', function (data) {
            var specs = $(data.elem).val();
            var materialType = $(this).parents("tr").find('select[name=materialType]').val();
            var qqProjectCode = $("#qqProjectCode").find("option:selected").val();
            $(this).parents(".materialtr").find('input[name=amount]').val('');
            if(isBlank(materialType)){
                return "";
            }
            var that_ = $(this);
            $.ajax({
                type:"POST",
                url:"${ctx}/material/apply/fingMaterialPrice",
                data:{
                    specs:specs,
                    materialType:materialType,
                    qqProjectCode:qqProjectCode
                },
                success:function(result){
                    that_.parents(".materialtr").find('.materialPrice').val(result);
                    that_.parents(".materialtr").find('.salesPrice').text(result);
                }
            });

        })

        function provinceOrder(province,_city){
            $("#city").empty();
            $("#area").empty();
            if(isBlank(province)){
                $("#city").append("<option value=''>请选择</option>");
                return "";
            }
            $.ajax({
                type:"POST",
                url:"${ctx}/main/redirect/getCitysByProName",
                data:{
                    province:province
                },
                success:function(result){
                    if(result =="205"){
                        layer.msg("暂无数据!")
                        return
                    }
                    var html =" <option value=''>请选择</option>";
                    for(var i=0;i<result.length;i++){
                        var city = result[i];
                        if(city.columns.CityName==_city){
                            html =html+ '<option value="'+city.columns.CityName+'" selected title="'+city.columns.CityID+'">'+city.columns.CityName+'</option>';
                        }else{
                            html =html+ '<option value="'+city.columns.CityName+'" <c:if test=""> selected</c:if> title="'+city.columns.CityID+'">'+city.columns.CityName+'</option>';
                        }
                    }
                    console.log(_city)
                    if(!isBlank(_city)){
                        $("#city").val(_city)
                    }
                    $("#city").append(html);
                    form.render('select');
                }
            });

        }

        function cityOrder(city,arean){
            $("#area").empty()
            if(isBlank(city)){
                $("#area").append("<option value=''>请选择</option>");
                return "";
            }
            $.ajax({
                type:"POST",
                url:"${ctx}/main/redirect/getAreaByCityName",
                data:{
                    city:city
                },
                success:function(result){
                    if(result =="205"){
                        layer.msg("暂无数据!")
                        return
                    }
                    var html ="<option value=''>请选择</option>";
                    for(var i=0;i<result.length;i++){
                        var area = result[i];
                        html =html+ '<option value="'+area.columns.DistrictName+'" >'+area.columns.DistrictName+'</option>';
                    }
                    $("#area").append(html);
                    if(!isBlank(arean)){
                        $("#area").val(arean)
                    }

                    form.render('select');
                }
            });

        }
    })

    function budget(){
        var totalAmount = 0;
        var type =  $("select[name='type']").val();

        if("1"==type){
            totalAmount = $(".entryOrder").find(".totalAmount").val();
        }else{
            totalAmount = $(".zizhuOrder").find(".totalAmount").val();
        }
        if(isBlank(totalAmount)){
            layer.msg("物料无金额信息", {time: 1000});
            return
        }
        var  entryIds= $("#entryIds").val();

        $.ajax({
            url: '${ctx}/account/budgetForCreditBalance',
            type: 'post',
            data: {
                totalAmount: totalAmount,
                entryIds:entryIds,
                type:type
            },
            success: function (res) {
                if(res.code =='200'){
                    layer.open({
                        title: '提示'
                        ,content: "您当前授信余额："+res.data+"，满足本次赊销申请预算金额！"
                    });
                    $('#save').removeClass("layui-btn-disabled");
                    $("#save").removeAttr("disabled")
                }else if(res.code =='201'){
                    layer.msg(res.errMsg, {time: 2000});
                }else{
                    layer.open({
                        title: '提示'
                        ,content: "您当前授信余额："+res.data+"，不满足本次赊销申请预算金额！请先确认授信余额！"
                    });
                    $('#save').addClass("layui-btn-disabled");
                    $("#save").prop("disabled",true)
                }
            },
            error: function (data) {
            }
        });
    }

    function inputAmount(){
        var $trs = $('#materialBody').find(".materialtr");
        var totalAmount=0;
        for (var i = 0; i < $trs.length; i++) {
            var $tr = $trs.eq(i);
            var amount = $tr.find('input[name=amount]').val();
            var price = $tr.find('.materialPrice').val();
            totalAmount = totalAmount +(amount*price);
        }

        $(".totalAmountHtml").html('预算金额：'+totalAmount+' 元');
        $(".totalAmount").val(totalAmount);
        $('#save').addClass("layui-btn-disabled");
        $(".totalTable").removeClass("hide");
    }

    function inputEntryAmount(){
        var $trs = $('#entryMaterialBody').find("tr");
        var totalAmount=0;
        for (var i = 0; i < $trs.length; i++) {
            var $tr = $trs.eq(i);
            var amount = $tr.find('input[name=amount]').val();
            var price = $tr.find('.materialPrice').val();
            totalAmount = totalAmount +(amount*price);
        }

        $(".totalAmountHtml").html('预算金额：'+totalAmount+' 元');
        $(".totalAmount").val(totalAmount);
        $('#save').addClass("layui-btn-disabled");
        $(".totalTable").removeClass("hide");
    }
    function closeDiv() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);
    }

    function isBlank(val) {
        if (val == null || val == '' || val == undefined) {
            return true;
        }
        return false;
    }
    function delImg(that, id) {
        $("#" + id).show();
        $(that).parent().remove();
    }

    function previewUrl(_url) {
        if (!checkUrl(_url)) {
            return false;
        }
        var base = new Base64();
        var b64Encoded = base.encode(_url);
        if(_url.endsWith('pdf')){
            window.open('http://47.98.203.224:8012/onlinePreview?url=' + encodeURIComponent(b64Encoded)+'&officePreviewType=pdf');
        }else{
            window.open('http://47.98.203.224:8012/onlinePreview?url=' + encodeURIComponent(b64Encoded));
        }
    }

    function checkUrl(url) {
        //url= 协议://(ftp的登录信息)[IP|域名](:端口号)(/或?请求参数)
        var strRegex = '^((https|http|ftp)://)'//(https或http或ftp)
            + '(([\\w_!~*\'()\\.&=+$%-]+: )?[\\w_!~*\'()\\.&=+$%-]+@)?' //ftp的user@  可有可无
            + '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 3位数字.3位数字.3位数字.3位数字
            + '|' // 允许IP和DOMAIN（域名）
            + '(localhost)|'	//匹配localhost
            + '([\\w_!~*\'()-]+\\.)*' // 域名- 至少一个[英文或数字_!~*\'()-]加上.
            + '\\w+\\.' // 一级域名 -英文或数字  加上.
            + '[a-zA-Z]{1,6})' // 顶级域名- 1-6位英文
            + '(:[0-9]{1,5})?' // 端口- :80 ,1-5位数字
            + '((/?)|' // url无参数结尾 - 斜杆或这没有
            + '(/[\\w_!~*\'()\\.;?:@&=+$,%#-]+)+/?)$';//请求参数结尾- 英文或数字和[]内的各种字符
        var re = new RegExp(strRegex, 'i');//i不区分大小写
        //将url做uri转码后再匹配，解除请求参数中的中文和空字符影响
        if (re.test(encodeURI(url))) {
            return (true);
        } else {
            return (false);
        }
    }

    // 新增组件
    function addtr(that) {
        $(that).addClass("layui-hide");
        $(that).next().removeClass('layui-hide');
        var html = '';
        html += '<tr class="materialtr">';
        html += '<td></td>';
        html += '<td >';
        html += '<select class="materialType" name="materialType" lay-filter="materialType">';
        html += '<option value="">请选择</option>';
        <c:forEach var="type" items="${typeList}">
        html += '<option value="${type.columns.id}">${type.columns.name}</option>';
          </c:forEach>

        html += '</select>';
        html += '</td>';
        html += '<td>';
        html += '<select class="materialSpecs" name="materialSpecs" lay-filter="materialSpecs">';
        html += '</select>';
        html += '</td>';
        html += '<td class="salesPrice"></td>'
        html += '<td><input type="text" class="layui-input" name="amount" onkeyup="inputAmount()"/><input type="hidden" class="materialPrice"/></td>';
        html += '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger addDaili" onclick="addtr(this)">添加</button>';
        html += '<button type="button" class="layui-btn layui-btn-sm layui-btn-danger deleteBut" onclick="delete1(this)">删除</button></td>';
        html += '</tr>';
        $("#materialBody").append(html);
        form.render('select');
        $('#materialBody>tr').each(function (i) {
            $(this).find('td:first').html(i + 1);
        });
    }

    function delete1(that) {
        if (!$(that).parents(".materialtr").next().hasClass("materialtr")) {
            $(that).parents(".materialtr").prev().find(".addDaili").removeClass("layui-hide");
        }
        $(that).closest('tr').remove();
        if ($('#materialBody>tr').length < 2) {
            $('#materialBody>tr').find(".addDaili").removeClass("layui-hide");
            $('#materialBody>tr').find(".deleteBut").addClass("layui-hide");
        }
        appendMSort();
        inputAmount()
    }

    function appendMSort() {
        $('#materialBody>tr').each(function (i) {
            $(this).find('td:first').html(i + 1);
        });
    }

    function getCustomerEntryList(obj){
        var deatil ="";
        for(var i =0;i<obj.length;i++){
            var entryObj=obj[i];
            deatil += ' <tr data-entryId="'+entryObj.entryId+'" >';
            deatil += '<td class="idx"></td>';
            deatil += '<td class="powerStationCode">'+entryObj.powerStationCode+'</td>';
            deatil += '<td class="tenantName">'+entryObj.tenantName+'</td>';
            deatil += '<td class="customerAddress">'+entryObj.customerAddress+'</td>';
            deatil += ' <td class="designCapacity">'+entryObj.designCapacity+'</td>';
            deatil += ' <td class="createTime">'+entryObj.createTime+'</td>';
            deatil += ' <td> ';
            deatil += '<a class="layui-table-opt-link" onclick="deleteEntry(this)">删除</a> ';
            deatil += ' </td> ';
        }
        $("#entryListBody").append(deatil);

        getIndex();
    }

    function getIndex() {

        var entryIds="";
        $("#entryListBody tr").each(function (index) {
            $(this).find(".idx").text(index + 1);
            if(isBlank(entryIds)){
                entryIds = $(this).attr("data-entryId");
            }else{
                entryIds = entryIds+","+$(this).attr("data-entryId");
            }
        })
      $("#entryIds").val(entryIds)
        var qqProjectCode = $("#qqProjectCode").find("option:selected").val();
        //获取电站的所有物料信息
        $.ajax({
            url: '${ctx}/material/apply/fingMaterialList',
            type: 'post',
            data: {
                entryIds: entryIds,
                qqProjectCode:qqProjectCode
            },
            success: function (res) {
                var materials ="";
                var totalAmount=0;
                $("#entryMaterialBody").empty();
                for(var i =0;i<res.length;i++) {
                    var mate = res[i];
                    var materType="";
                    if(mate.columns.type == '1'){
                        materType="逆变器";
                    }else if(mate.columns.type == '2'){
                        materType="并网箱";
                    }else if(mate.columns.type == '3'){
                        materType="组件";
                    }else if(mate.columns.type == '4'){
                        materType="支架";
                    }
                    materials += ' <tr data-typeId="' + materType + '" >';
                    materials += '<td class="idx"></td>';

                    materials += '<td class="materType">' + materType + '</td>';
                    materials += '<td class="materialSpecs">' +mate.columns.model + '</td>';
                    materials += '<td class="salesPrice">' +mate.columns.price + '</td>';
                    materials += '<td><input type="text" class="layui-input" name="amount" value="' + mate.columns.num + '" onkeyup="inputEntryAmount()"/><input type="hidden" class="materialPrice" value="'+mate.columns.price+'"/></td>';
                    materials += '<td> ';
                    materials += '<a class="layui-table-opt-link" onclick="deleteMaterial(this)">删除</a> ';
                    materials += ' </td> ';
                    totalAmount = totalAmount+(mate.columns.num * mate.columns.price);
                }
                $("#entryMaterialBody").append(materials);
                $(".entryMates .totalAmountHtml").html('预算金额：'+totalAmount+' 元');
                $(".entryMates .totalAmount").val(totalAmount);
                $(".entryMates .totalTable").removeClass("hide")
                appendSort();

            },
            error: function (data) {
            }
        });
    }
    function appendSort() {
        $('#entryMaterialBody>tr').each(function (i) {
            $(this).find('td:first').html(i + 1);
        });
    }
    //删除
    function deleteMaterial(that) {
        $(that).parents("tr").remove();
        appendSort()
        inputEntryAmount()
    }

    //删除
    function deleteEntry(that) {
        $(that).parents("tr").remove();
        getIndex();
    }


</script>
</body>
</html>
