<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <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>
        .layui-form-select dl {
            max-height: 200px;
            width: 80%;
        }

        html {
            background-color: #fff;
        }

        .layui-table td, .layui-table th {
            text-align: center;
        }

        .hx_l {
            position: relative;
        }

        .hx_l > span {
            position: absolute;
            right: 10px;
            top: 5px
        }

        .layui-inline {
            margin-top: 10px;
        }

        .layui-textarea {
            min-height: 50px;
        }
    </style>
</head>
<body>
<div class="aaa">
    <div class="layui-form">
        <div class="layui-card-body pt-20 pb-40 h-350" action="" id="detailSet">
            <div class="layui-col-xs12 mb-10 pr-30">
                <blockquote class="layui-elem-quote" style="margin-left: 0;background-color: #fff;">退货信息</blockquote>
                <div class="layui-col-xs12">
                    <div class="layui-inline layui-col-xs4">
                        <label class="layui-form-label w-100"><i class="red">*</i>订单编号：</label>
                        <div class="layui-input-block ml-100 w-200">
                            <input type="text" name="relationNumber" id="relationNumber" lay-verify="required"
                                   autocomplete="off" class="layui-input" value="${order.columns.relation_number}">
                            <input class="hide" id="id" value="${order.columns.id}">
                        </div>
                    </div>
                    <div class="layui-inline layui-col-xs4">
                        <label class="layui-form-label w-140"><i class="red">*</i>退货方式：</label>
                        <div class="layui-input-block w-200">
                            <select name="returnMethod" id="returnMethod" lay-verify="required"
                                    lay-filter="returnMethod">
                                <option value="">请选择</option>
                                <c:forEach var="deliveryMethod" items="${deliveryMethodList}">
                                    <option value="${deliveryMethod.columns.id}"
                                            datatype="${deliveryMethod.columns.type}"
                                            <c:if test="${deliveryMethod.columns.id eq order.columns.return_method_id}">selected</c:if>
                                    >${deliveryMethod.columns.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-xs4 method_logistics" <c:if test="${order.columns.return_method_name ne '快递物流'}">style="display: none;"</c:if> >
                        <label class="layui-form-label w-140"><i class="red">*</i>物流单号：</label>
                        <div class="layui-input-block ml-140">
                            <input type="text" name="expressNo" id="expressNo" value="${order.columns.express_no}"
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs12">
                    <div class="layui-inline layui-col-xs4 method_other" <c:if test="${order.columns.return_method_name eq '快递物流'}">style="display: none;"</c:if> >
                        <label class="layui-form-label w-100"><i class="red">*</i>司机：</label>
                        <div class="layui-input-block ml-100">
                            <input type="text" name="retrunDriver" id="retrunDriver" autocomplete="off"
                                   class="layui-input" value="${order.columns.return_driver}">
                        </div>
                    </div>
                    <div class="layui-inline layui-col-xs4 method_other" <c:if test="${order.columns.return_method_name eq '快递物流'}">style="display: none;"</c:if> >
                        <label class="layui-form-label w-140"><i class="red">*</i>联系方式：</label>
                        <div class="layui-input-block ml-140">
                            <input type="text" name="returnMobile" id="returnMobile" autocomplete="off"
                                   class="layui-input" value="${order.columns.return_mobile}">
                        </div>
                    </div>
                    <div class="layui-inline layui-col-xs4 method_other" <c:if test="${order.columns.return_method_name eq '快递物流'}">style="display: none;"</c:if> >
                        <label class="layui-form-label w-140"><i class="red">*</i>车牌号：</label>
                        <div class="layui-input-block ml-140">
                            <input type="text" name="returnCarNum" id="returnCarNum" autocomplete="off"
                                   class="layui-input" value="${order.columns.return_car_num}">
                        </div>
                    </div>
                </div>

                <div class="layui-inline layui-col-xs12">
                    <label class="layui-form-label w-130">退货备注：</label>
                    <div class="layui-input-block w-200 hx_l">
                        <textarea name="returnRemark" id="returnRemark"
                                  class="layui-textarea">${order.columns.return_remark}</textarea>
                    </div>
                </div>
            </div>
            <input type="hidden" name="details" lay-verify="details">
            <div class="layui-col-xs12 mb-20 pr-30">
                <blockquote class="layui-elem-quote" style="margin-left: 0;background-color: #fff;">物料信息</blockquote>
                <div class="layui-inline layui-col-xs4">
                    <label class="layui-form-label w-140"><i class="red">*</i>出库仓库：</label>
                    <div class="layui-input-block w-200">
                        <select name="warehouse" id="warehouse" lay-verify="required">
                            <c:forEach var="warehouse" items="${warehouseList}">
                                <option value="${warehouse.columns.id}"
                                        <c:if test="${warehouse.columns.id eq order.columns.warehouse_id}">selected</c:if>
                                >${warehouse.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <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="materialTable">
                    <c:forEach items="${details}" var="detail" varStatus="vs">
                        <tr data-id="${detail.columns.material_id}">
                            <td>${vs.count}</td>
                            <td>${detail.columns.material_code}</td>
                            <td>${detail.columns.material_name}</td>
                            <td>${detail.columns.material_type}</td>
                            <td>${detail.columns.material_brand}</td>
                            <td>${detail.columns.material_spec}</td>
                            <td>${detail.columns.deliver_num}</td>
                            <td>${detail.columns.returnedNum}</td>
                            <td>
                                <input type="text" class="layui-input" name="num" value="${detail.columns.return_num}" width="80px;"/>
                                <input class="layui-hide" name="applyAmount" value="${detail.columns.order_num}" />
                                <input class="layui-hide" name="costPrice" value="${detail.columns.cost_price}" />
                                <input class="layui-hide" name="salesPrice" value="${detail.columns.sales_price}" />
                            </td>
                            <td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="layui-form-item operate-footer" style="text-align: center;">
            <input type="button" lay-submit lay-filter="confirm" id="confirm" class="layui-btn " value="保存">
            <button type="button" class="layui-btn layui-btn-primary " onclick="closeDiv();">取消</button>
        </div>
    </div>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script src="${ctxPlugin}/lib/xm-select.js"></script>
<script type="text/javascript">
    //初始数据
    var $form;
    var form;
    var upload;
    var $;
    layui.use(['form', 'table', 'upload', 'jquery'], function () {
        $ = layui.jquery;
        form = layui.form;
        upload = layui.upload;
        $form = $('form');

        // 监听盘点仓库下拉选
        form.on('select(returnMethod)', function (data) {
            var returnMethod = $("#returnMethod").find("option:selected").attr("datatype");
            if (isBlank(returnMethod)) {
                $(".method_logistics").hide();
                $(".method_other").hide();
            } else {
                if (returnMethod === '0') {
                    $(".method_logistics").show();
                    $(".method_other").hide();
                } else {
                    var returnMethodId = $("#returnMethod").val();
                    getReturnMethodDetail(returnMethodId);
                    $(".method_logistics").hide();
                    $(".method_other").show();
                }
            }
        });

        $('#relationNumber').change(function () {
            var relationNumber = $("#relationNumber").val();
            if (isBlank(relationNumber)) {
                return
            }
            searchVal(relationNumber)
        })

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

        function searchVal(relationNumber) {
            $.ajax({
                type: 'post',
                url: '${ctx}/material/return/findDeliverOrderByNumber',
                data: {code: relationNumber, belongType: "2"},
                async: false,
                dataType: 'json',
                success: function (d) {
                    console.log(d)
                    var warehouseId = '';
                    var html = '';
                    for (var i = 0; i < d.length; i++) {
                        html += '<tr data-id="' + d[i].columns.material_id + '" >'
                            + '<td ></td>'
                            + '<td>' + d[i].columns.code + '</td>'
                            + '<td>' + d[i].columns.material_name + '</td>'
                            + '<td>' + d[i].columns.material_type + '</td>'
                            + '<td>' + d[i].columns.material_brand + '</td>'
                            + '<td>' + d[i].columns.material_spec + '</td>'
                            + '<td>' + d[i].columns.in_amount + '</td>'
                            + '<td>' + d[i].columns.returnNum + '</td>'
                            + '<td><input type="text" class="layui-input" name="num" width="80px;"/>'
                            + '<input class="layui-hide" name="applyAmount" value="' + d[i].columns.apply_amount + '"  />'
                            + '<input class="layui-hide" name="costPrice" value="' + d[i].columns.purchase_price + '"  />'
                            + '<input class="layui-hide" name="salesPrice" value="' + d[i].columns.sales_price + '"  />'
                            + '</td>'
                            + '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>'
                            + '</tr>';
                    }
                    $('#materialTable').empty().append(html);
                    appendSort();
                    if (!isBlank(warehouseId)) {
                        $("#warehouse").val(warehouseId);
                    }
                }
            });
        }

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


        var saveFlag = true;
        form.on('submit(confirm)', function (data) {
            if (!saveFlag) {
                return;
            }
            var bom = {};
            bom.id = '${order.columns.id}';
            bom.relationNumber = $("#relationNumber").val();
            bom.warehouseId = $("#warehouse").val();
            bom.warehouseName = $("#warehouse").find("option:selected").text();
            bom.returnMethodId = $("#returnMethod").val();
            bom.returnMethodName = $("#returnMethod").find("option:selected").text();
            var returnMethod = $("#returnMethod").find("option:selected").attr("datatype");
            if (returnMethod === '0' && isBlank(data.field.expressNo)) {
                layer.msg("请输入物流单号");
                return;
            }
            if (returnMethod != '0' && isBlank(data.field.retrunDriver)) {
                layer.msg("请输入司机");
                return;
            }
            if (returnMethod != '0' && isBlank(data.field.returnMobile)) {
                layer.msg("请输入联系方式");
                return;
            }
            if (returnMethod != '0' && isBlank(data.field.returnCarNum)) {
                layer.msg("请输入车牌号");
                return;
            }
            bom.expressNo = data.field.expressNo;
            bom.retrunDriver = data.field.retrunDriver;
            bom.returnMobile = data.field.returnMobile;
            bom.returnCarNum = data.field.returnCarNum;
            bom.returnRemark = data.field.returnRemark;
            bom.type = "1";
            var arr = [];
            var verifyFlag = false;
            $('#materialTable>tr').each(function () {
                var material = {};
                material.materialId = $(this).attr("data-id");
                material.sort = $(this).find('td').eq(0).text();
                material.materialCode = $(this).find('td').eq(1).text();
                material.materialName = $(this).find('td').eq(2).text();
                material.materialType = $(this).find('td').eq(3).text();
                material.materialBrand = $(this).find('td').eq(4).text();
                material.materialSpec = $(this).find('td').eq(5).text();
                material.outAmount = $(this).find('td').eq(6).text();
                var returnNum = $(this).find('td').eq(7).text();
                material.num = $(this).find('td').eq(8).find('input[name=num]').val();
                if (isBlank(material.num) || parseFloat(material.num) == 0) {
                    //退货数量为空或0的物料不进行退货操作
                } else if (!/^\d+(\.\d{1,2})?$/.test(material.num)) {
                    layer.msg("第" + material.sort + "行退货数量格式不正确");
                    verifyFlag = true;
                    return false;
                } else {
                    var sumNum = material.num;
                    if (!isBlank(returnNum)) {
                        sumNum = parseFloat(sumNum) + parseFloat(returnNum);
                    }
                    if (parseFloat(sumNum) > parseFloat(material.outAmount)) {
                        layer.msg("第" + material.sort + "行退货总数量不能大于签收数量");
                        verifyFlag = true;
                        return false;
                    }
                    material.applyAmount = $(this).find('td').eq(8).find('input[name=applyAmount]').val();
                    material.costPrice = $(this).find('td').eq(8).find('input[name=costPrice]').val();
                    material.salesPrice = $(this).find('td').eq(8).find('input[name=salesPrice]').val();
                    arr.push(material);
                }
            });
            if (arr.length == 0) {
                layer.msg("物料不能为空");
                return;
            }
            bom.details = arr;
            if (verifyFlag) {
                return;
            }
            saveFlag = false;
            $.ajax({
                url: '${ctx}/material/return/saveReturnOrder',
                method: 'post',
                contentType: 'application/json',
                data: JSON.stringify(bom),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code == "200") {
                        parent.layer.msg("保存成功", {time: 1000});
                        closeDiv();
                        parent.reload();
                    } else if (res.code == "501") {
                        layer.msg(res.errMsg, {time: 2000}, function () {
                            saveFlag = true;
                        });
                    } else if (res.code == '422') {
                        layer.msg(res.msg, {time: 1500}, function () {
                            saveFlag = true;
                        });
                    } else {
                        layer.msg("保存失败", {time: 1000});
                        saveFlag = true;
                    }
                },
                complete: function () {

                }
            });
        });
    })

    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 getReturnMethodDetail(returnMethodId) {
        if (isBlank(returnMethodId)) {
            return;
        }
        $.ajax({
            url: "${ctx}/material/return/getReturnMethodDetail",
            type: "POST",
            data: {returnMethodId: returnMethodId},
            success: function (result) {
                if (!isBlank(result)) {
                    var data = result.columns;
                    $("#retrunDriver").val(data.driver_name);
                    $("#returnMobile").val(data.mobile);
                    $("#returnCarNum").val(data.car_number);
                }
            }
        })
    }

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

