<%@ 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;
    }
    .download-link {
        display: inline-block;
        padding-top: 5px;
        padding-right: 16px;
        color: #007bff;
        text-decoration: none;
        border-radius: 4px;
    }

    .download-link:hover {
        color: #0056b3;
    }
    </style>
</head>

<body>
<div class="layui-form">

<div class="layui-tab-content">
    <div class="layui-card">

     <%--   <c:if test="${order.columns.purchase_order_examine_status == '2'}">
            <div class="ideaOpe">
                审核意见：${order.columns.audit_remark}
            </div>
        </c:if>--%>
        <div class="layui-elem-quote" style="display: flex;justify-content: space-between;">
            <p>订单信息</p>
            <p style="color: #D9B589;">下单时间：<fmt:formatDate value="${order.columns.create_time}" pattern="yyyy-MM-dd HH:mm:ss"/></p>
        </div>
        <div class="layui-tab-content">
            <div class="layui-row">
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">订单编号：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="inWarehouseName" readonly autocomplete="off"
                               placeholder="请输入"
                               class="layui-input layui-bg-gray" value="${order.columns.number}">
                    </div>
                </div>
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">订单状态：</label>
                    <div class="layui-input-block ">
                        <c:choose>
                            <c:when test="${order.columns.status eq '1'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="待审批"></c:when>
                            <c:when test="${order.columns.status eq '2'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="待分配"></c:when>
                            <c:when test="${order.columns.status eq '3'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="分配打回"></c:when>
                            <c:when test="${order.columns.status eq '4'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="采购审批"></c:when>
                            <c:when test="${order.columns.status eq '5'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="待发货"></c:when>
                            <c:when test="${order.columns.status eq '6'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="待签收"></c:when>
                            <c:when test="${order.columns.status eq '7'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="已完成"></c:when>
                            <c:when test="${order.columns.status eq '9'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="发货驳回"></c:when>
                            <c:when test="${order.columns.status eq 'a'}"><input type="text" disabled name="status"
                                                                                 readonly
                                                                                 class="layui-input layui-bg-gray"
                                                                                 value="发货审核驳回"></c:when>
                        </c:choose>
                    </div>
                </div>
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">订单来源：</label>
                    <div class="layui-input-block">
                        <c:if test="${order.columns.type eq '1'}"><input type="text" disabled name="type" readonly
                                                                         class="layui-input layui-bg-gray"
                                                                         value="电站下单"></c:if>
                        <c:if test="${order.columns.type eq '2'}"><input type="text" disabled name="type" readonly
                                                                         class="layui-input layui-bg-gray"
                                                                         value="物料储备"></c:if>
                        <c:if test="${order.columns.type eq '3'}"><input type="text" disabled name="type" readonly
                                                                         class="layui-input layui-bg-gray"
                                                                         value="平台采购"></c:if>
                        <c:if test="${order.columns.type eq '4'}"><input type="text" disabled name="type" readonly
                                                                         class="layui-input layui-bg-gray"
                                                                         value="合并发货"></c:if>
                        <c:if test="${order.columns.type eq '5'}"><input type="text" disabled name="type" readonly
                                                                         class="layui-input layui-bg-gray"
                                                                         value="材料下单"></c:if>
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">入库仓库：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="inWarehouseName" readonly class="layui-input layui-bg-gray"
                               value="${order.columns.inWarehouseName}">
                    </div>
                </div>
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">接货人：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="personInCharge" readonly class="layui-input layui-bg-gray"
                               value="${order.columns.person_in_charge}">
                    </div>
                </div>
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">联系方式：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="mobile" readonly class="layui-input layui-bg-gray"
                               value="${order.columns.mobile}">
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-xs8">
                    <label class="layui-form-label ">仓库地址：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="mobile" readonly class="layui-input layui-bg-gray"
                               value="${order.columns.w_address}">
                    </div>
                </div>
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">代理商名称：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="mobile" readonly class="layui-input layui-bg-gray"
                               value="${order.columns.applyOrderTrader}">
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-xs4">
                    <label class="layui-form-label ">企企项目：</label>
                    <div class="layui-input-block ">
                        <input type="text" disabled name="qqProjectName" readonly class="layui-input layui-bg-gray" value="${order.columns.qqProjectName}">
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-xs12">
                    <label class="layui-form-label">订单备注：</label>
                    <div class="layui-input-block ">
                        <textarea readonly class="layui-textarea layui-bg-gray">${order.columns.remarks}</textarea>
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-inline layui-col-xs12">
                    <label class="layui-form-label">施工人员保单：</label>
                    <div class="layui-input-block img-box ml-120">
                        <div style="display: flex">
                            <div id="insuranceFilesDiv">
                                <c:if test="${not empty order.columns.insurance_files}">
                                    <c:forEach items="${order.columns.insurance_files}" var="file" varStatus="vs">
                                        <div style="margin-top: 5px">
                                            <a style="color:#2890ac;" href="${commonStaticImgPath}${file}" download="${file}" class="download-link">${fns:substringAfterLast(file, '/')}</a>
                                            <a style="color:#2890ac;cursor: pointer" target="_blank" onclick="previewUrl('${commonStaticImgPath}${file}')"    class="download-link">查看</a>
                                            <input type="hidden" class="insuranceFiles" value="${file}">
                                        </div>
                                        <c:set var="insuranceFilesCount" value="${vs.count}"/>
                                    </c:forEach>
                                </c:if>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <%--
            <div class="layui-row">
                <div class="layui-inline layui-col-xs12">
                    <label class="layui-form-label">安全教育登记表：</label>
                    <div class="layui-input-block img-box ml-120">
                        <div style="display: flex">
                            <div id="safetyFilesDiv">
                                <c:if test="${not empty order.columns.safety_files}">
                                    <c:forEach items="${order.columns.safety_files}" var="file" varStatus="vs">
                                        <div style="margin-top: 5px">
                                            <a style="color:#2890ac;" href="${commonStaticImgPath}${file}" download="${file}" class="download-link">${fns:substringAfterLast(file, '/')}</a>
                                            <a style="color:#2890ac;cursor: pointer" target="_blank" onclick="previewUrl('${commonStaticImgPath}${file}')"    class="download-link">查看</a>
                                            <input type="hidden" class="safetyFiles" value="${file}">
                                        </div>
                                        <c:set var="safetyFilesCount" value="${vs.count}"/>
                                    </c:forEach>
                                </c:if>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
           --%>
            <div class="layui-row pt-20">
                <div class="layui-col-xs4">
                    <label class="layui-form-label"><span class="red">*</span>发货仓库：</label>
                    <div class="layui-input-block ">
                        <select name="outWarehouse"  lay-search lay-filter="outWarehouse"  id="outWarehouse">
                            <option value="">请选择</option>
                            <c:forEach items="${warehouses}" var="item">
                                <option value="${item.columns.id}">${item.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
            </div>

            <c:if test="${order.columns.status eq '4' && not empty order.columns.warehouse_fail_reason}">
                <div class="layui-form-item mb-5">
                    <label class="layui-form-label w-130">打回原因：</label>
                    <div class="layui-input-block ">
                                    <textarea readonly
                                              class="layui-textarea layui-bg-gray">${order.columns.warehouse_fail_reason}</textarea>
                    </div>
                </div>
            </c:if>
        </div>
        <div class="layui-elem-quote" style="display: flex;justify-content: space-between;">
            <p>物料清单</p>
            <%--<p>采购总额：<span class="red">${total}</span>元</p>--%>
        </div>
        <div class="layui-tab-content">
            <div class="layui-row">
                <table class="layui-table">
                    <thead>
                    <th>序号</th>
                    <th>物料代码</th>
                    <th>物料名称</th>
                    <th>物料类型</th>
                    <th>物料规格</th>
                    <th>物料品牌</th>
                    <th>单位</th>
<%--                    <th>采购单价</th>--%>
                    <th>销售价</th>
                    <th>申请数量</th>
                    <th>最小发货单位</th>
                    <th>发货数量</th>
                    <th>本次发货数量</th>
                    <th>库存数量</th>
                    </thead>
                    <tbody id="materialTbody">
                    <c:forEach items="${details}" var="applyDetail" varStatus="vs">
                        <tr data-id="${applyDetail.columns.id}" data-materialId="${applyDetail.columns.material_id}"
                            data-applyAmount="${applyDetail.columns.out_amount}">
                            <td>${vs.count}</td>
                            <td>${applyDetail.columns.code}</td>
                            <td>${applyDetail.columns.material_name}</td>
                            <td>${applyDetail.columns.materialTypeName}</td>
                            <td>${applyDetail.columns.material_spec}</td>
                            <td>${applyDetail.columns.material_brand}</td>
                            <td>${applyDetail.columns.unit_name}</td>
<%--                            <td><input type="text" class="layui-input" name="purchasePrice" value='${applyDetail.columns.purchase_price}'/></td>--%>
                            <td><input type="text" class="layui-input" name="salesPrice" value='${applyDetail.columns.sales_price}'/></td>
                            <td>${applyDetail.columns.apply_amount}</td>
                            <td>${applyDetail.columns.min_apply_amount}</td>
<%--                            <td><input type="text" class="layui-input" name="outAmount" value='<fmt:formatNumber value="${applyDetail.columns.out_amount}" pattern="#"/>'/></td>--%>
                            <td><fmt:formatNumber value="${applyDetail.columns.out_amount}" pattern="#"/></td>
                            <td><input type="text" class="layui-input amount" name="amount" value='<fmt:formatNumber value="${applyDetail.columns.out_amount}" pattern="#"/>'/></td>
                            <td></td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
    <div class="operate-footer">
<%--        <input type="button" value="拆单" class="layui-btn " onclick="splitOrder();">--%>
        <input type="button" onclick="allocation()" value="分配" class="layui-btn ">
        <input type="button" onclick="reject()" value="驳回" class="layui-btn ">
        <button type="button" class="layui-btn layui-btn-primary " onclick="closeDiv();">取消</button>
    </div>

</div>
<%--<div class="hide pd-10 layui-form" style="padding: 10px" id="allocationDiv">--%>
<%--    <div class="layui-row">--%>
<%--        <div class="layui-col-xs12">--%>
<%--            <div class="layui-form-item">--%>
<%--                <label class="layui-form-label"><span class="red">*</span>发货单位：</label>--%>
<%--                <div class="layui-input-block ">--%>
<%--                    <select name="deliverId" lay-filter="deliverId" lay-search>--%>
<%--                        <option value="">请选择</option>--%>
<%--                        <option value="a">平台发货</option>--%>
<%--                        <c:forEach var="item" items="${supplies}">--%>
<%--                            <option value="${item.columns.id}">${item.columns.name}</option>--%>
<%--                        </c:forEach>--%>
<%--                    </select>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--        </div>--%>
<%--    </div>--%>
<%--    <div class="layui-row">--%>
<%--        <div class="layui-col-xs12">--%>
<%--            <div class="layui-form-item">--%>
<%--                <label class="layui-form-label"><span class="red">*</span>发货仓库：</label>--%>
<%--                <div class="layui-input-block ">--%>
<%--                    <select name="outWarehouse" lay-search>--%>
<%--                        <option value="">请选择</option>--%>
<%--                        <c:forEach items="${warehouses}" var="item">--%>
<%--                            <option value="${item.columns.id}">${item.columns.name}</option>--%>
<%--                        </c:forEach>--%>
<%--                    </select>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--        </div>--%>
<%--    </div>--%>
<%--    <div class="layui-row">--%>
<%--        <div class="layui-col-xs12">--%>
<%--            <div class="layui-form-item">--%>
<%--                <label class="layui-form-label w-130">分配说明：</label>--%>
<%--                <div class="layui-input-block ">--%>
<%--                    <textarea class="layui-textarea" id="allocationRemark"></textarea>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--        </div>--%>
<%--    </div>--%>

<%--</div>--%>
<div class="hide layui-tab-content" id="auditDiv">
    <label class="layui-form-label"><span class="red">*</span>驳回原因：</label>
    <div class="layui-input-block ">
        <textarea id="reason" class="layui-textarea"></textarea>
    </div>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.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 priceReg = /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/;
    var priceReg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
    var numReg = /^[0-9]\d*$/;
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['form', 'layedit', 'laydate', 'jquery', 'layer', 'element', 'upload'], function () {
        $ = layui.jquery;
        form = layui.form;
        var element = layui.element;
        $form = $('form');

        form.verify({
            express: function (value) {
                var expressMethod = $('select[name=deliverMethodId]').find('option:selected').data('type');
                if (isBlank(value) && expressMethod === 0) {
                    return '请填写物流单号';
                }
            },
            deliverInvoice: function (value) {
                if (isBlank(value)) {
                    return '请上传接货单';
                }
            }
        });

        if (${not empty order.columns.deliver_invoice}) {
            $('#pic').show();
        }

        <c:if test="${opt eq 'view'}">
        $('input,select,textarea').prop('disabled', true);
        form.render();
        layer.photos({
            photos: '.layer-photos-demo'
            , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        });
        </c:if>

        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#uploader' //绑定元素
            , url: '${ctx}/common/uploadFile' //上传接口
            , size: 5 * 1024
            , number: 1
            , accept: 'file'
            , exts: 'jpg|png|gif|doc|docx|ppt|pdf|xls|xlsx|txt|mp4|mp3|avi|mov|rmvb|rm|flv|3gp|apk'
            , done: function (res) {
                if (res.code > 0) {
                    return layer.msg("上传失败！", {icon: 2});
                }
                var imgPath = res.path;
                $('#pic').attr('href', '${commonStaticImgPath}' + imgPath).html(res.filename); //图片链接（base64）
                $("#pic").removeClass("hide");
                //$("#uploader").hide();
                $("#deliverInvoice").val(imgPath);
            }
            , error: function () {
                //请求异常回调 演示失败状态
            }
        });

        //选择仓库获取库存数量
        form.on('select(outWarehouse)', function (data) {
            var outWarehouseId = $(data.elem).find("option:selected").val();
            var materialId = '';
            $("#materialTbody tr").each(function (index) {
                var $tr = $(this);
                materialId = $tr.data('materialid');
                $.ajax({
                    type: "POST",
                    url: "${ctx}/material/getStockByWarehouse",
                    data: {
                        outWarehouseId:outWarehouseId,
                        materialId: materialId
                    },
                    success: function (result) {
                        console.log("返回的库存数量："+result)
                        $tr.find('td').eq(12).text(result);
                    }
                });
            })

        });

        form.on('select(deliverMethodId)', function (d) {
            var $elem = $(d.elem);
            var $expressNo = $('.expressNoDiv');
            var $otherDiv = $('.otherDiv');
            if ($elem.find('option:selected').data('type') === 0) {
                $expressNo.removeClass('layui-hide');
                $otherDiv.addClass('layui-hide');
            } else {
                $expressNo.addClass('layui-hide');
                $otherDiv.removeClass('layui-hide')
            }
        });

        var deliverFlag = true;
        form.on('submit(deliver)', function (d) {
            if (!deliverFlag) {
                return;
            }
            var arr = getListData();
            var total = 0;
            for (var i = 0; i < arr.length; i++) {
                if (!/^\d+(\.\d{1,2})?$/.test(arr[i].amount)) {
                    layer.msg('第' + (i + 1) + '条数量格式不正确');
                    return;
                }
                if (arr[i].amount * 1 > arr[i].applyAmount * 1) {
                    layer.msg('第' + (i + 1) + '条数量不能超过下单数量');
                    return;
                }
                total += arr[i].amount * 1;
            }
            if (total === 0) {
                layer.msg('发货数量不能为0');
                return;
            }

            deliverFlag = false;
            $.ajax({
                type: 'post',
                url: '${ctx}/material/order/doDeliver',
                contentType: 'application/json',
                data: JSON.stringify({
                    deliverMethodId: d.field.deliverMethodId,
                    expressNo: d.field.expressNo,
                    deliverRemark: d.field.deliverRemark,
                    deliverInvoice: d.field.deliverInvoice,
                    deliverDriver: d.field.deliverDriver,
                    deliverMobile: d.field.deliverMobile,
                    deliverCarNum: d.field.deliverCarNum,
                    type: '1',
                    materialInfo: {
                        orderId: '${order.columns.id}',
                        details: arr
                    }
                }),
                dataType: 'json',
                success: function (data) {
                    afterSuccess(data);
                },
                complete: function () {
                    deliverFlag = true;
                }
            });
        });

        // 发货单位下拉事件
        // form.on('select(deliverId)', function (data) {
        //     var deliverId = data.value;
        //     var $outWarehouse = $('select[name=outWarehouse]');
        //     if (deliverId === 'a') {
        //
        //         $outWarehouse.closest('.layui-row').removeClass('layui-hide');
        //     } else {
        //         $outWarehouse.closest('.layui-row').addClass('layui-hide');
        //
        //     }
        // });

    })

    var temporaryflag = true;

    function temporary() {
        if (!temporaryflag) {
            return;
        }
        temporaryflag = false;
        var deliverMethodId = $("#deliverMethodId").val();
        var expressNo = $("input[name='expressNo']").val();
        var deliverRemark = $("#deliverRemark").val();
        var deliverDriver = $("input[name='deliverDriver']").val();
        var deliverMobile = $("input[name='deliverMobile']").val();
        var deliverCarNum = $("input[name='deliverCarNum']").val();
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/doTemporary',
            data: {
                deliverMethodId: deliverMethodId,
                expressNo: expressNo,
                deliverRemark: deliverRemark,
                deliverDriver: deliverDriver,
                deliverMobile: deliverMobile,
                deliverCarNum: deliverCarNum,
                orderId: '${order.columns.id}'
            },
            dataType: 'json',
            success: function (data) {
                if (data.code === '200') {
                    layer.msg('操作成功', {icon: 1});
                    window.location.href = '${ctx}/material/order/toDeliverPage?opt=fh&id=${order.columns.id}';
                } else if (data.code === '501') {
                    layer.msg(data.errMsg, {icon: 2});
                } else {
                    layer.msg('操作失败', {icon: 2});
                }

            },
            complete: function () {
                deliverFlag = true;
            }
        });
    }


    function printOrder() {
        var id = '${order.columns.id}';
        layer.open({
            title: '打印',
            type: 2,
            area: ['85%', '85%'],
            fixed: false,
            content: '${ctx}/material/order/printOrder?applyId=' + id,
            success: function (layero, index) {
                childWin = window[layero.find('iframe')[0]['name']];
            }
        })
    }

    var splitFlag = true;

    function splitOrder() {
        if (!splitFlag) {
            return;
        }
        var arr = getListData();
        var total = 0;
        for (var i = 0; i < arr.length; i++) {
            if (isBlank(arr[i].amount)) {
                continue;
            }
            if (!/^[1-9]\d*$/.test(arr[i].amount)) {
                layer.msg('第' + (i + 1) + '条拆单数量格式不正确');
                return;
            }
            if (arr[i].amount * 1 > arr[i].applyAmount * 1) {
                layer.msg('第' + (i + 1) + '条拆单数量不能超过发货数量');
                return;
            }
            total += arr[i].amount * 1;
        }
        if (total === 0) {
            layer.msg('请填写拆单数量');
            return;
        }

        splitFlag = false;
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/splitDeliverOrder',
            contentType: 'application/json',
            data: JSON.stringify({
                orderId: '${order.columns.id}',
                details: arr
            }),
            dataType: 'json',
            success: function (data) {
                afterSuccess(data);
            },
            complete: function () {
                splitFlag = true;
            }
        });

    }
    function reject() {
        $('#reason').val('');
        layer.open({
            type: 1,
            area: ['450px', '280px'],
            content: $("#auditDiv"),
            title: '提示',
            btn: ['确认', '取消'],
            btnAlign: 'c',
            yes: function () {
                var reason = $('#reason').val();
                $.ajax({
                    type: 'post',
                    url: '${ctx}/material/order/allocationReject',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({
                        id: '${order.columns.id}',
                        reason: reason
                    }),
                    success: function (result) {
                        if (result.code === '200') {
                            layer.msg('操作成功！', {time: 1000}, function(){
                                parent.layer.closeAll();
                                parent.$('.layui-laypage-btn').click();
                            })
                        } else {
                            layer.msg('保存失败!'+result.errMsg)
                        }
                    }
                });

            }
        })
    }

    // 分配
    function allocation() {
        // $("#allocationDiv").find("input").val("");
        // $('select[name=deliverId]').val('');
        // $('select[name=outWarehouse]').val('');
        // $('#allocationRemark').val('');

        var outWarehouse = $('#outWarehouse').find("option:selected").val();
        if (isBlank(outWarehouse)) {
            layer.msg('请选择发货仓库');
            return;
        }

        var $trs = $('#materialTbody>tr');
        var details = [];//本次发货明细
        var detailFlag = false;
        var arry= [];
        var splitOrderFlag = true;//拆单标识
        var splitDetails = [];//拆单明细
        var totalAmount = 0;
        for (var i = 0; i < $trs.length; i++) {
            var $tr = $trs.eq(i);
            var brand = $tr.find("td").eq(5).html();
            if(!isBlank(arry) && !$.inArray($.trim(brand),arry)){
                layer.msg('物料不属于同一个供应商，不可直接分配');
                detailFlag = true;
                return false;
            }
            var detail = {};
            var splitDetail = {};
            detail.detailId = $tr.data('id');
            splitDetail.detailId = $tr.data('id');
            splitDetail.materialId = $tr.data('materialid');
            splitDetail.applyAmount = $tr.data('applyamount');
            var salesPrice = $tr.find('input[name=salesPrice]').val();
            if (!priceReg.test(salesPrice)) {
                layer.msg('第'+(i+1)+'行销售价格式不正确');
                detailFlag = true;
                return false;
            }
            detail.salesPrice = salesPrice;
            // var purchasePrice = $tr.find('input[name=purchasePrice]').val();
            //  if (!priceReg.test(purchasePrice)) {
            //      layer.msg('第'+(i+1)+'行采购单价格式不正确');
            //      detailFlag = true;
            //      return false;
            //  }
            //  detail.purchasePrice = purchasePrice;

            var outAmount = $tr.find("td").eq(10).text();
            if (!numReg.test(outAmount)) {
                layer.msg('第'+(i+1)+'行发货数量格式不正确');
                detailFlag = true;
                return false;
            }
            //库存数量
            var stockAmount = $tr.find("td").eq(12).text();
            //最小发货单位
            var minApplyAmount = $tr.find("td").eq(9).text();
            //本次发货数量
            var amount = $tr.find('input[name=amount]').val();
            if (isBlank(amount)){
                layer.msg('第'+(i+1)+'行本次发货数量格式不正确');
                detailFlag = true;
                return false;
            }
            if (!numReg.test(amount)) {
                layer.msg('第'+(i+1)+'行本次发货数量格式不正确');
                detailFlag = true;
                return false;
            }
            if (amount % minApplyAmount != 0){
                layer.msg('第'+(i+1)+'行本次发货数量不是最小发货单位的整数倍');
                detailFlag = true;
                return false;
            }
            if (amount-outAmount>0){
                layer.msg('第'+(i+1)+'行本次发货数量大于发货数量');
                detailFlag = true;
                return false;
            }
            if (amount-stockAmount>0){
                layer.msg('第'+(i+1)+'行本次发货数量大于库存数量');
                detailFlag = true;
                return false;
            }
            detail.outAmount = amount;
            totalAmount += amount;
            details.push(detail);
            //需要拆单
            if (amount-outAmount<0){
                splitOrderFlag = false
                splitDetail.amount =outAmount - amount;
                splitDetails.push(splitDetail);
            }
            arry.push(detail);
        }

        if (totalAmount == 0){
            layer.msg('请至少选择一个物料发货');
            return ;
        }
        if (detailFlag) {
            return;
        }
        if(splitOrderFlag){
            //不需要拆单  直接分配
            $.ajax({
                type: 'post',
                url: '${ctx}/material/order/allocation',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    id: '${order.columns.id}',
                    deliverId: 'a',
                    outWarehouseId: outWarehouse,
                    allocationRemark: '',
                    details: details
                }),
                success: function (result) {
                    if (result.code === '200') {
                        layer.msg('操作成功！', {time: 1000}, function(){
                            parent.layer.closeAll();
                            parent.$('.layui-laypage-btn').click();
                        })
                    } else {
                        layer.msg('保存失败!'+result.errMsg)
                    }
                }
            });
        }else {
            //需要拆单  TODO
            console.log("需要拆单");
            $.ajax({
                type: 'post',
                url: '${ctx}/material/order/splitDeliverOrder',
                contentType: 'application/json',
                data: JSON.stringify(
                    {
                        id: '${order.columns.id}',
                        deliverId: 'a',
                        outWarehouseId: outWarehouse,
                        allocationRemark: '',
                        details: details,
                        <%--orderId: '${order.columns.id}',--%>
                        splitDetails:splitDetails,
                    }
                ),
                dataType: 'json',
                success: function (data) {
                    afterSuccess(data);
                },
                complete: function () {
                    splitFlag = true;
                }
            });

        }




        <%--layer.open({--%>
        <%--    type: 1,--%>
        <%--    area: ['50%', '50%'],--%>
        <%--    content: $("#allocationDiv"),--%>
        <%--    title: '提示',--%>
        <%--    btn: ['确认', '取消'],--%>
        <%--    btnAlign: 'c',--%>
        <%--    yes: function () {--%>

        <%--        var deliverId = $('select[name=deliverId]').val();--%>
        <%--        if (isBlank(deliverId)) {--%>
        <%--            layer.msg('请选择发货单位');--%>
        <%--            return;--%>
        <%--        }--%>
        <%--        var outWarehouse = $('select[name=outWarehouse]').val();--%>
        <%--        if (isBlank(outWarehouse)) {--%>
        <%--            layer.msg('请选择发货仓库');--%>
        <%--            return;--%>
        <%--        }--%>
        <%--        var allocationRemark = $('#allocationRemark').val();--%>
        <%--        var $trs = $('#materialTbody>tr');--%>
        <%--        var details = [];--%>
        <%--        var detailFlag = false;--%>
        <%--        var splitAmount = 0;--%>
        <%--        var arry= [];--%>
        <%--        for (var i = 0; i < $trs.length; i++) {--%>
        <%--            var $tr = $trs.eq(i);--%>
        <%--            var brand = $tr.find("td").eq(4).html();--%>
        <%--            if(!isBlank(arry) && !$.inArray($.trim(brand),arry)){--%>
        <%--                layer.msg('物料不属于同一个供应商，不可直接分配');--%>
        <%--                detailFlag = true;--%>
        <%--                return false;--%>
        <%--            }--%>
        <%--            var detail = {};--%>
        <%--            detail.detailId = $tr.data('id');--%>
        <%--            var salesPrice = $tr.find('input[name=salesPrice]').val();--%>
        <%--            if (!priceReg.test(salesPrice)) {--%>
        <%--                layer.msg('第'+(i+1)+'行销售价格式不正确');--%>
        <%--                detailFlag = true;--%>
        <%--                return false;--%>
        <%--            }--%>
        <%--            detail.salesPrice = salesPrice;--%>
        <%--           /* var purchasePrice = $tr.find('input[name=purchasePrice]').val();--%>
        <%--            if (!priceReg.test(salesPrice)) {--%>
        <%--                layer.msg('第'+(i+1)+'行采购单价格式不正确');--%>
        <%--                detailFlag = true;--%>
        <%--                return false;--%>
        <%--            }--%>
        <%--            detail.purchasePrice = purchasePrice;*/--%>
        <%--            var outAmount = $tr.find('input[name=outAmount]').val();--%>
        <%--            if (!numReg.test(outAmount)) {--%>
        <%--                layer.msg('第'+(i+1)+'行发货数量格式不正确');--%>
        <%--                detailFlag = true;--%>
        <%--                return false;--%>
        <%--            }--%>
        <%--            detail.outAmount = outAmount;--%>
        <%--            details.push(detail);--%>
        <%--            var amount = $tr.find('input[name=amount]').val();--%>
        <%--            splitAmount = splitAmount + (isBlank(amount) ? 0 : amount);--%>
        <%--            arry.push(detail);--%>
        <%--        }--%>
        <%--        if (splitAmount > 0) {--%>
        <%--            layer.msg('存在拆单数量，请先拆单！');--%>
        <%--            return;--%>
        <%--        }--%>
        <%--        if (detailFlag) {--%>
        <%--            return;--%>
        <%--        }--%>
        <%--        $.ajax({--%>
        <%--            type: 'post',--%>
        <%--            url: '${ctx}/material/order/allocation',--%>
        <%--            contentType: 'application/json',--%>
        <%--            dataType: 'json',--%>
        <%--            data: JSON.stringify({--%>
        <%--                id: '${order.columns.id}',--%>
        <%--                // deliverId: deliverId,--%>
        <%--                outWarehouseId: outWarehouse,--%>
        <%--                allocationRemark: allocationRemark,--%>
        <%--                details: details--%>
        <%--            }),--%>
        <%--            success: function (result) {--%>
        <%--                if (result.code === '200') {--%>
        <%--                    layer.msg('操作成功！', {time: 1000}, function(){--%>
        <%--                        parent.layer.closeAll();--%>
        <%--                        parent.$('.layui-laypage-btn').click();--%>
        <%--                    })--%>
        <%--                } else {--%>
        <%--                    layer.msg('保存失败!'+result.errMsg)--%>
        <%--                }--%>
        <%--            }--%>
        <%--        });--%>

        <%--    }--%>
        <%--});--%>
    }

    function getListData() {
        var $trs = $('#materialTbody>tr');
        var arr = [];
        for (var i = 0; i < $trs.length; i++) {
            var $tr = $trs.eq(i);
            var data = {};
            data.detailId = $tr.data('id');
            data.materialId = $tr.data('materialid');
            data.applyAmount = $tr.data('applyamount');
            data.amount = $tr.find('input[name=amount]').val();
            if (isBlank(data.amount)) {
                continue;
            }
            arr.push(data);
        }
        return arr;
    }

    function afterSuccess(data) {
        if (data.code === '200') {
            parent.layer.msg('操作成功', {icon: 1});
            closeDiv();
            parent.searchOrder();
        } else if (data.code === '501') {
            layer.msg(data.errMsg, {icon: 2});
        } else {
            layer.msg('操作失败', {icon: 2});
        }
    }

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


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