<%@ 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;}
    </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 name="type" lay-verify="required" lay-filter="orderType">
                                <option value="5" selected>购买</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"></textarea>
                            </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="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">
            <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>
                                <th>申请数量</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="optionalMaterialBody">
                            <tr>
                                <td data-id="" >1</td>
                                <td><select class="materialSpecs" name="materialSpecs" lay-filter="materialSpecs">
                                    <option value="">请选择</option>
                                    <c:forEach var="re" items="${recordList}">
                                        <option value="${re.columns.id}">${re.columns.material_specs} * ${re.columns.material_name}</option>
                                    </c:forEach>

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

        <div class="layui-form-item operate-footer" style="text-align: center;">
            <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" value="提交">

        </div>

    </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,
                    materialTypeId: '4'
                }, '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_brand + '</td>'
                + '<td>' + d.material_specs + '</td>'
                + '<td>' + d.unit + '</td>'
                + '<td>' + d.remarks + '</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="deleteMaterial(this)">删除</button></td>'
                + '</tr>';

            var $trs ;

                $trs = $('#optionalMaterialBody>tr');

            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) {
                    $('#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'
            });
        });

        window.importZjMaterialApply = function(data){

            var zizhuhtml ="";
            var ziin=1;
            for(var i=0; i<data.materialList.length; i++){
                var d = data.materialList[i];
                if(d.type=='4'){
                    zizhuhtml += '<tr>'
                        + '<td data-id="' + d.materialId + '" >' + ziin + '</td>'
                        + '<td>' + d.code + '</td>'
                        + '<td>' + d.name + '</td>'
                        + '<td>' + d.materialBrand + '</td>'
                        + '<td>' + d.materialSpecs + '</td>'
                        + '<td>' + d.unit + '</td>'
                        + '<td>' + d.remarks + '</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="deleteMaterial(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);
            });
        }
        form.on('select(qqProjectCode)',function(data){
        $('#optionalMaterialBody').html('');
            var html = `<tr>
                                <td data-id="" >1</td>
                                <td><select class="materialSpecs" name="materialSpecs" lay-filter="materialSpecs">
                                    <option value="">请选择</option>
                                    <c:forEach var="re" items="${recordList}">
                                        <option value="${re.columns.id}">${re.columns.material_specs} * ${re.columns.material_name}</option>
                                    </c:forEach>

                                </select></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td style="width: 15%"></td>
                                <td style="width: 5%"></td>
                                </tr>`;
            $('#optionalMaterialBody').append(html);
            form.render('select');
        });

        form.on('select(materialSpecs)',function(data){
            var value = $(data.elem).find("option:selected").val();
            var qqProjectCode = $("#qqProjectCode").find("option:selected").val();
            var that_ = $(this);
          //  var tr_ = that_.parents("tr");
            var $trs = $('#optionalMaterialBody>tr');
            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 === value) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                $.ajax({
                    url:"${ctx}/material/apply/findMaterialByCode",
                    type:"POST",
                    data:{
                        id:value,
                        qqProjectCode:qqProjectCode
                    }
                    ,success:function (result) {

                        if(result.code =="200"){
                            var _data = result.data;
                            var unit = (_data.unitName===undefined)?'':_data.unitName;
                            var remarks = (_data.remarks===undefined)?'':_data.remarks;
                            var html = '<tr>'
                                + '<td data-id="' + _data.id + '" ></td>'
                                + '<td>' + _data.materialSpecs + '</td>'
                                + '<td>' + _data.code + '</td>'
                                + '<td>' + _data.materialName + '</td>'
                                + '<td>' + _data.materialBrand + '</td>'
                                + '<td>' + _data.customerPrice + '</td>'
                                + '<td>' + unit + '</td>'
                                + '<td>' + remarks + '</td>'
                                + '<td><input type="text" class="layui-input" name="amount" lay-verify="required" onkeyup="inputAmount()"/><input type="hidden" class="materialPrice" value="'+_data.customerPrice+'"/></td>'
                                + '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="deleteMaterial(this)">删除</button></td>'
                                + '</tr>';
                            $('#optionalMaterialBody').prepend(html);
                            appendOpSort();
                            $(".materialSpecs").val('');
                            form.render('select');
                        }
                    }
                })
            } else {
                layer.msg('物料已存在');
                $(".materialSpecs").val('');
                form.render('select');
            }


        })


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

        })
        var cheSavw = false;
        form.on('submit(save)', function (data) {
            $("#save").attr("disabled", "true");
            if(cheSavw){
                console.log("应该退出")
                return;
            }
            let insuranceFiles = "";
            $(".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;
            // }
            var $trszi = $('#optionalMaterialBody>tr');
            if ($trszi.length === 0) {
                $("#save").removeAttr("disabled");
                layer.msg('请添加物料');
                return;
            }
            var arr = [];
            for (var i = 0; i < $trszi.length; i++) {
                var obj = {};
                var $tr = $trszi.eq(i);
                var $fisrtTd = $tr.find('td:first');
                var targetId = $fisrtTd.data('id');
                if(isBlank(targetId)){
                    continue;
                }
                obj.targetId = targetId;
                obj.amount = $tr.find('input[name=amount]').val();
                if (!/^\d+(\.\d{1,3})?$/.test(obj.amount)) {
                    $("#save").removeAttr("disabled");
                    layer.msg('第' + (i + 1) + '行申请数量格式不正确');
                    return;
                }
                let price = $tr.find('td').eq(5).text();
                if (price === '0'){
                    $("#save").removeAttr("disabled");
                    layer.msg('第' + (i + 1) + '行物料价格暂未维护');
                    return;
                }
                arr.push(obj);
            }
            cheSavw = true;

            if (arr.length < 1) {
                $("#save").removeAttr("disabled");
                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,
                    details: arr,
                    insuranceFiles:insuranceFiles,
                    safetyFiles:safetyFiles,
                    qqProjectCode:qqProjectCode
                }),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code === "200") {
                        layer.msg("保存成功", {time: 1000}, function(){
                            parent.layer.closeAll()
                            parent.searchOrder();
                        });
                    } else if (res.code === '501') {
                        $("#save").removeAttr("disabled");
                        layer.msg(res.errMsg);
                        cheSavw = false;
                    } else {
                        $("#save").removeAttr("disabled");
                        layer.msg("保存失败", {time: 1000});
                        cheSavw = false;
                    }
                },
                error: function (data) {
                }
            });
        });
        var tepChec = false;
        form.on('submit(templeSave)', function (data) {
            $("#templeSave").attr("disabled", "true");
            if(tepChec){
                return 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();
                }
            });
            var $trszi = $('#optionalMaterialBody>tr');
            if ($trszi.length === 0) {
                layer.msg('请添加物料');
                return;
            }
            var arr = [];
            for (var i = 0; i < $trszi.length; i++) {
                var obj = {};
                var $tr = $trszi.eq(i);
                var $fisrtTd = $tr.find('td:first');
                var targetId = $fisrtTd.data('id');
                if(isBlank(targetId)){
                    continue;
                }
                obj.targetId = targetId;
                obj.amount = $tr.find('input[name=amount]').val();
                if (!/^\d+(\.\d{1,3})?$/.test(obj.amount)) {
                    $("#templeSave").removeAttr("disabled");
                    layer.msg('第' + (i + 1) + '行申请数量格式不正确');
                    return;
                }
                let price = $tr.find('td').eq(5).text();
                if (price === '0'){
                    $("#templeSave").removeAttr("disabled");
                    layer.msg('第' + (i + 1) + '行物料价格暂未维护');
                    return;
                }
                arr.push(obj);
            }
            tepChec = true;
            if (arr.length < 1) {
                layer.msg('请添加物料');
                $("#templeSave").removeAttr("disabled");
                tepChec = 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({
                    actionType:'1',
                    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,
                    details: arr,
                    insuranceFiles:insuranceFiles,
                    safetyFiles:safetyFiles,
                    qqProjectCode:qqProjectCode,
                }),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code === "200") {
                        layer.msg("保存成功", {time: 1000}, function(){
                            parent.layer.closeAll()
                            parent.location.reload(true);
                        });
                    } else if (res.code === '501') {
                        $("#templeSave").attr("disabled", "true");

                        layer.msg(res.errMsg);
                    } else {
                        $("#templeSave").attr("disabled", "true");
                        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);

        });


        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 inputAmount(){
        var $trs = $('#optionalMaterialBody>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();
            if(isBlank(amount)){
                continue
            }
            var price = $tr.find('.materialPrice').val();
            totalAmount = totalAmount +(amount*price).toFixed(2)*1;
        }

        $(".totalAmountHtml").html('总金额：'+totalAmount+' 元');
        $(".totalAmount").val(totalAmount);
        $(".totalTable").removeClass("hide");
    }
    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 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 appendSort() {
        $('#optionalMaterialBody>tr').each(function (i) {
            $(this).find('td:first').html(i + 1);
        });
    }

    //删除
    function deleteMaterial(that) {
        $(that).parents("tr").remove();
        appendSort();
        inputAmount();
    }

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