<%@ 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;} .xm-body .scroll-body{max-height: 110px !important;}</style>
</head>

<body>
<div class="layui-form">
    <div class="layui-card">
        <div class="layui-col-xs12 mt-10 mb-10 pr-30">
            <div class="layui-inline layui-col-xs4">
                <label class="layui-form-label w-130">入库仓库：</label>
                <div class="layui-input-block ">
                    <input type="text" disabled name="inWarehouseName" readonly autocomplete="off" placeholder="请输入"
                           class="layui-input layui-bg-gray" value="${apply.columns.inWarehouseName}">
                </div>
            </div>
            <div class="layui-inline layui-col-xs4">
                <label class="layui-form-label w-130">下单人：</label>
                <div class="layui-input-block ">
                    <input type="text" disabled name="creator" readonly autocomplete="off" placeholder="请输入"
                           class="layui-input layui-bg-gray" value="${apply.columns.traderName}">
                </div>
            </div>
            <div class="layui-inline layui-col-xs4">
                <label class="layui-form-label w-130">申请时间：</label>
                <div class="layui-input-block ">
                    <input type="text" disabled name="createTime" readonly autocomplete="off" placeholder="请输入"
                           class="layui-input layui-bg-gray"
                           value="<fmt:formatDate value="${apply.columns.create_time}" pattern="yyyy-MM-dd HH:mm"/>">
                </div>
            </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 readonly class="layui-textarea layui-bg-gray">${apply.columns.remark}</textarea>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 mb-10 pr-30 pl-30">
            <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                <ul class="layui-tab-title">
                    <li class="layui-this">物料清单</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <!-- 待匹配的订单可以编辑 -->
                        <c:if test="${apply.columns.status eq '5'}">
                            <div>
                                <div class="f-r mb-10">
                                    <button class="layui-btn layui-btn-xs saveFuc editBtn">编辑</button>
                                    <button class="layui-btn layui-btn-xs saveFuc layui-hide saveBtn">保存</button>
                                    <button class="layui-btn layui-btn-xs saveFuc layui-hide cancelBtn">取消</button>
                                </div>
                            </div>
                        </c:if>
                        <div class="needHide">
                            <table class="layui-table">
                                <thead>
                                <th>序号</th>
                                <th><input type="checkbox" lay-skin="primary" lay-filter="all"/></th>
                                <th>物料代码</th>
                                <th>物料类型</th>
                                <th>物料组</th>
                                <th>单位</th>
                                <th>物料描述</th>
                                <th>申请数量</th>
                                <th>拆单/下单数量</th>
                                </thead>
                                <tbody id="materialTbody">
                                <c:forEach items="${applyDetails}" var="applyDetail" varStatus="vs">
                                    <tr data-id="${applyDetail.columns.id}"
                                        data-materialId="${applyDetail.columns.material_id}"
                                        data-applyAmount="${applyDetail.columns.apply_amount}">
                                        <td>${vs.count}</td>
                                        <td><input type="checkbox" lay-filter="one" lay-skin="primary"/></td>
                                        <td>${applyDetail.columns.code}</td>
                                        <td>${applyDetail.columns.materialTypeName}</td>
                                        <td>${applyDetail.columns.materialGroupName}</td>
                                        <td>${applyDetail.columns.unit_name}</td>
                                        <td>${applyDetail.columns.remarks}</td>
                                        <td>${applyDetail.columns.apply_amount}</td>
                                        <td><input type="text" class="layui-input" name="amount" value="${applyDetail.columns.apply_amount}"/></td>
                                    </tr>
                                </c:forEach>
                                </tbody>
                            </table>
                        </div>
                        <div class="layui-hide editDiv">
                            <div class="layui-col-xs12 mb-10 pr-30">
                                <div class="layui-inline layui-col-xs6">
                                    <label class="layui-form-label">代码：</label>
                                    <div class="layui-input-block">
                                        <div id="code"></div>
                                    </div>
                                </div>
                                <div class="layui-inline layui-col-xs6">
                                    <label class="layui-form-label">描述：</label>
                                    <div class="layui-input-block">
                                        <div id="desc"></div>
                                    </div>
                                </div>
                            </div>
                            <table class="layui-table">
                                <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>物料代码</th>
                                    <th>物料类型</th>
                                    <th>物料组</th>
                                    <th>物料描述</th>
                                    <th>申请数量</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="materialBody">
                                <c:forEach items="${applyDetails}" var="detail" varStatus="vs">
                                    <tr>
                                        <td data-id="${detail.columns.material_id}" data-type="1">${vs.count}</td>
                                        <td>${detail.columns.code}</td>
                                        <td>${detail.columns.materialTypeName}</td>
                                        <td>${detail.columns.materialGroupName}</td>
                                        <td>${detail.columns.remarks}</td>
                                        <td><input type="text" class="layui-input" value="${detail.columns.apply_amount}" name="amount" lay-verify="required"/></td>
                                        <td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>
                                    </tr>
                                </c:forEach>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="operate-footer">
        <input type="button" value="拆单" class="layui-btn needHide" onclick="splitOrder();">
        <input type="button" value="下单" class="layui-btn needHide" onclick="placeOrder(true);">
        <input type="button" value="驳回" class="layui-btn needHide" onclick="notPass();">
        <input type="button" value="取消" class="layui-btn layui-btn-primary " onclick="closeDiv();">
    </div>
</div>
<div class="hide pd-10 layui-form" style="padding: 10px" id="ideaDiv">
    <div class="layui-form-item">
        <label class="layui-form-label w-130"><span class="red">*</span>出库仓库：</label>
        <div class="layui-input-block ">
            <select name="outWarehouse" lay-search>

            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label w-130">下单备注：</label>
        <div class="layui-input-block ">
            <textarea class="layui-textarea orderRemark"></textarea>
        </div>
    </div>
</div>
<div class="hide pd-10" style="padding: 10px" id="auditDiv">
    <label class="layui-form-label w-130"><span class="red">*</span>驳回原因：</label>
    <div class="layui-input-block ">
        <textarea id="idea" class="idea-text f-l layui-textarea"></textarea>
    </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 $;
    var imgs = '';
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['form', 'layedit', 'laydate', 'jquery', 'layer', 'element'], function () {
        $ = layui.jquery;
        form = layui.form;
        var element = layui.element;
        $form = $('form');

        form.on('checkbox(all)', function (d) {
            if ($(d.elem).is(':checked')) {
                $('#materialTbody').find('input[type=checkbox]').prop('checked', true);
            } else {
                $('#materialTbody').find('input[type=checkbox]').prop('checked', false);
            }
            form.render();
        });

        form.on('checkbox(one)', function (d) {
            var $tbody = $('#materialTbody');
            var $all = $('input[lay-filter="all"]');
            if ($tbody.find('input[type=checkbox]:checked').length === $tbody.find('input[type=checkbox]').length) {
                $all.prop('checked', true);
            } else {
                $all.prop('checked', false);
            }
            form.render();
        });

        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
                }, 'code');
            },
            on: function (data) {
                if (data.isAdd && data.arr.length > 0) {
                    appendTr(data);
                }
            }
        });

        var descXm = xmSelect.render({
            el: '#desc',
            name: 'desc',
            radio: true,
            tips: '请输入查询',
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (val, cb, show) {
                searchVal(val, cb, {
                    desc: val
                }, 'remarks');
            },
            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 + '" data-type="' + d.type + '"></td>'
                + '<td>' + d.code + '</td>'
                + '<td>' + d.material_type + '</td>'
                + '<td>' + d.material_group + '</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="del(this)">删除</button></td>'
                + '</tr>';
            var $trs = $('#materialBody>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) {
                $('#materialBody').append(html);
            } else {
                layer.msg('物料/BOM已存在');
            }
            appendSort();
            data.arr.length = 0;
            codeXm.reset();
            descXm.reset();
        }

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

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

        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++) {
                            if (d[i].type === '1') {
                                var data = {};
                                data.name = d[i][filed];
                                data.value = d[i].id;
                                data.origin = d[i];
                                arr.push(data);
                            }
                        }
                        cb(arr);
                    }
                });
            } else {
                cb([]);
            }
        }

        $('.editBtn').click(function(){
            $('.editDiv').removeClass("layui-hide");
            $('.needHide').addClass('layui-hide');
            $('.saveFuc').toggleClass('layui-hide');
        });

        $('.cancelBtn').click(function(){
            $('.editDiv').addClass("layui-hide");
            $('.needHide').removeClass('layui-hide');
            $('.saveFuc').toggleClass('layui-hide');
        });

        $('.saveBtn').click(function(){
            var $trs = $('#materialBody>tr');
            if ($trs.length === 0) {
                layer.msg('请添加物料/BOM');
                return;
            }
            var arr = [];
            for (var i = 0; i < $trs.length; i++) {
                var obj = {};
                var $tr = $trs.eq(i);
                var $fisrtTd = $tr.find('td:first');
                obj.targetId = $fisrtTd.data('id');
                obj.type = $fisrtTd.data('type');
                obj.amount = $tr.find('input[name=amount]').val();
                if (!/^\d+(\.\d{1,2})?$/.test(obj.amount)) {
                    layer.msg('第' + (i + 1) + '行申请数量格式不正确');
                    return;
                }
                arr.push(obj);
            }
            $.ajax({
                url: '${ctx}/material/apply/modifyApplyOrder',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify({
                    id: '${apply.columns.id}',
                    inWarehouseId: '${apply.columns.in_warehouse_id}',
                    province:'w',
                    city:'w',
                    area:'w',
                    address:'w',
                    personInCharge:'${apply.columns.person_in_charge}',
                    mobile:'${apply.columns.mobile}',
                    details: arr
                }),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code === "200") {
                        parent.layer.msg("保存成功", {time: 1000});
                        location.reload();
                    } else if (res.code === '501') {
                        layer.msg(res.errMsg);
                    } else {
                        layer.msg("保存失败", {time: 1000});
                    }
                },
                error: function (data) {
                }
            });
        });
    })

    function getListData() {
        var $trs = $('#materialTbody>tr');
        var arr = [];
        for (var i = 0; i < $trs.length; i++) {
            var $tr = $trs.eq(i);
            if ($tr.find('input[type=checkbox]').is(':checked')) {
                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();
                arr.push(data);
            }
        }
        return arr;
    }

    var splitFlag = true;

    function splitOrder() {
        if (!splitFlag) {
            return;
        }
        var arr = getListData();
        if (arr.length === 0) {
            layer.msg('请勾选物料明细');
            return;
        }
        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;
            }
        }
        splitFlag = false;
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/splitOrder',
            contentType: 'application/json',
            data: JSON.stringify({
                orderId: '${apply.columns.id}',
                details: arr
            }),
            dataType: 'json',
            success: function (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});
                }
            },
            complete: function () {
                splitFlag = true;
            }
        });
    }

    var placeOrderFlag = true;

    function placeOrder(needChooseWarehouse) {
        if (!placeOrderFlag) {
            return;
        }
        var arr = getListData();
        if (arr.length === 0) {
            layer.msg('请勾选物料明细');
            return;
        }
        for (var i = 0; i < arr.length; i++) {
            if (!/^\d+(\.\d{1,2})?$/.test(arr[i].amount)) {
                layer.msg('第' + (i + 1) + '条下单数量格式不正确');
                return;
            }
            if (Number(arr[i].amount) === 0) {
                layer.msg('第' + (i + 1) + '条下单数量不能为0');
                return;
            }
            if (arr[i].amount * 1 > arr[i].applyAmount * 1) {
                layer.msg('第' + (i + 1) + '条下单数量不能超过申请数量');
                return;
            }
        }

        if (needChooseWarehouse) {
            chooseWarehouse(arr);
        } else {
            placeOrderFlag = false;
            var warehouseId = $('select[name=outWarehouse]').val();
            var orderRemark = $('textarea.orderRemark').val();
            $.ajax({
                type: 'post',
                url: '${ctx}/material/order/placeOrder',
                contentType: 'application/json',
                data: JSON.stringify({
                    orderId: '${apply.columns.id}',
                    details: arr,
                    warehouseId: warehouseId,
                    orderRemark: orderRemark
                }),
                success: function (data) {
                    afterSuccess(data);
                },
                complete: function () {
                    placeOrderFlag = true;
                }
            });
        }
    }

    function chooseWarehouse(arr) {
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/canOrderData',
            contentType: 'application/json',
            data: JSON.stringify({
                orderId: '${apply.columns.id}',
                details: arr
            }),
            dataType: 'json',
            success: function (data) {
                if (data.length === 0) {
                    layer.msg('未匹配到满足条件的出库仓库');
                    return;
                }
                var html = "<option value=''>请选择</option>";
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var warehouses = item.warehouseList;
                    html += '<optgroup label="' + item.name + '">';
                    for (var j = 0; j < warehouses.length; j++) {
                        html += '<option value ="' + warehouses[j].id + '">' + warehouses[j].name + '</option>';
                    }
                    html += '</optgroup>';
                }
                $('select[name=outWarehouse]').empty().append(html);
                openOrderWin();
            }
        });
    }

    function openOrderWin() {
        layer.open({
            type: 1,
            area: ['60%', '90%'],
            content: $("#ideaDiv"),
            title: '下单',
            btn: ['确认', '取消'],
            btnAlign: 'c',
            yes: function () {
                var warehouseId = $('select[name=outWarehouse]').val();
                if (isBlank(warehouseId)) {
                    layer.msg('请选择出库仓库', {icon: 2});
                    return;
                }
                placeOrder(false);
            },
            success: function () {
                form.render();
            }
        })
    }

    function notPass() {
        layer.open({
            type: 1,
            area: ['450px', '280px'],
            content: $("#auditDiv"),
            title: '审核驳回',
            btn: ['确认', '取消'],
            btnAlign: 'c',
            yes: function () {
                var idea = $('#idea').val();
                if (isBlank(idea)) {
                    layer.msg('请输入驳回原因', {icon: 2});
                    return;
                }
                ajaxAudit('1', idea);
            }
        })
    }

    var auditFlag = true;

    function ajaxAudit(type, reason, details) {
        if (!auditFlag) {
            return;
        }
        auditFlag = false;
        $.ajax({
            type: 'post',
            url: '${ctx}/material/order/auditOrder',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({
                orderId: '${apply.columns.id}',
                type: type,
                reason: reason,
                details: details
            }),
            success: function (data) {
                afterSuccess(data);
            },
            complete: function () {
                auditFlag = true;
            }
        });
    }

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


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