<%@ 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" 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
        }

        .hx_del {
            font-size: 12px;
            color: #0e8ee7;
            position: relative;
            top: 4px;
            display: none
        }

        #attachFile > li {
            height: 26px
        }

        #attachFile > li:hover .hx_del {
            display: inline-block
        }

        .hx_ts {
            font-size: 12px;
            color: red;
        }

        .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">
                <div class="layui-inline layui-col-xs4">
                    <label class="layui-form-label w-130"><i class="red">*</i>入库仓库：</label>
                    <div class="layui-input-block w-200">
                        <select name="inWarehouseId" lay-verify="required">
                            <option value="">请选择</option>
                            <c:forEach items="${inWarehouseList}" var="inWarehouse">
                                <option value="${inWarehouse.columns.id}" ${inWarehouse.columns.id eq order.inWarehouseId? 'selected': ''}>${inWarehouse.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="layui-inline layui-col-xs4">
                    <label class="layui-form-label w-130"><i class="red">*</i>供应商：</label>
                    <div class="layui-input-block w-200">
                        <select name="supplyId" lay-filter="supplyId" lay-verify="required">
                            <option value="">请选择</option>
                            <c:forEach var="supply" items="${supplyList}">
                                <option value="${supply.columns.id}"
                                        <c:if test="${order.deliverId eq supply.columns.id}">selected</c:if> >${supply.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="layui-inline layui-col-xs4">
                    <label class="layui-form-label w-130"><i class="red">*</i>出库仓库：</label>
                    <div class="layui-input-block w-200">
                        <select name="outWarehouseId" lay-verify="required">
                            <option value="">请选择</option>
                            <c:forEach items="${outWarehouseList}" var="outWarehouse">
                                <option value="${outWarehouse.columns.id}" ${outWarehouse.columns.id eq order.outWarehouseId? 'selected': ''}>${outWarehouse.columns.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-xs12 mb-10 pr-30">
                <label class="layui-form-label w-130">订单备注：</label>
                <div class="layui-input-block">
                    <textarea name="remarks" class="layui-textarea">${order.remarks}</textarea>
                </div>
            </div>

            <input type="hidden" name="details" lay-verify="details">


            <div class="layui-col-xs12 pr-30 mt-20">

                <div class="layui-inline layui-col-xs5">
                    <label class="layui-form-label">物料代码：</label>
                    <div class="layui-input-block">
                        <div id="code"></div>
                    </div>
                </div>
                <div class="layui-inline layui-col-xs5">
                    <label class="layui-form-label">物料描述：</label>
                    <div class="layui-input-block">
                        <div id="desc"></div>
                    </div>
                </div>
                <div class="layui-inline layui-col-xs2">
                    <label class="layui-form-label w-80"></label>
                    <input type="button" class="layui-btn layui-btn-sm" id="importPlan" value="批量导入"/>
                </div>
            </div>

            <div class="layui-col-xs12 mb-20 pr-30 mt-20">
                <table class="layui-table">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>物料代码</th>
                        <th>物料类型</th>
                        <th>物料组</th>
                        <th>单位</th>
                        <th>物料描述</th>
                        <th>下单数量</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="materialTable">
                    <c:forEach items="${details}" varStatus="vs" var="material">
                        <tr data-id="${material.columns.material_id}">
                            <td>${vs.count}</td>
                            <td>${material.columns.code}</td>
                            <td>${material.columns.materialTypeName}</td>
                            <td>${material.columns.materialGroupName}</td>
                            <td>${material.columns.unit_name}</td>
                            <td>${material.columns.remarks}</td>
                            <td class="amount">${material.columns.apply_amount}</td>
                            <td></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="${empty order? '保存': '重新提交'}">
            <button type="button" class="layui-btn layui-btn-primary " onclick="closeDiv();">取消</button>
        </div>
    </div>
</div>
<div id="lookImg" class="hide pos-r">
    <div style="position:relative;width:90%;height:450px;">
        <div class="w-500 h-450 lookImg">
            <img src="" width="80%" id="image">
        </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 $;
    var imgs = '';
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    var type = '${type}';
    layui.use(['form', 'table', 'upload', 'jquery'], function () {
        $ = layui.jquery;
        form = layui.form;
        upload = layui.upload;
        $form = $('form');

        form.on('select(supplyId)', function (d) {
            var $select = $('select[name=outWarehouseId]');
            $select.empty();
            if (!isBlank(d.value)) {
                $.ajax({
                    type: 'post',
                    url: '${ctx}/warehouseSetting/findWarehouseByAscriptionId',
                    async: false,
                    data: {
                        id: d.value
                    },
                    dataType: 'json',
                    success: function(data){
                        var html = '<option value="">请选择</option>';
                        for (var i = 0; i < data.length; i++) {
                            html += '<option value="' + data[i].columns.id + '">' + data[i].columns.name + '</option>';
                        }
                        $select.append(html);
                    }
                });
            }
            form.render();
        });

        form.verify({
            details: function () {
                if ($('#materialTable>tr').length === 0) {
                    return "请导入物料信息";
                }
            },
            attach: function (value) {
                if (isBlank(value)) {
                    return "请上传附件";
                }
            }
        });

        $(document).on('mouseenter', '#materialTable td', function () {
            var that = this;
            $(that).attr('title', $(that).text());
        });

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

        function appendTr(data) {
            console.log(data)
            var d = data.arr[0].origin;
            var html = '<tr data-id="' + d.id + '" >'
                + '<td ></td>'
                + '<td>' + d.code + '</td>'
                + '<td>' + d.material_type + '</td>'
                + '<td>' + d.material_group + '</td>'
                + '<td>' + d.unit + '</td>'
                + '<td>' + d.remarks + '</td>'
                + '<td><input type="text" class="layui-input" name="amount" lay-verify="required" width="80px;"/></td>'
                + '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>'
                + '</tr>';
            var $trs = $('#materialTable>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) {
                $('#materialTable').append(html);
            } else {
                layer.msg('物料/BOM已存在');
            }
            appendSort();
            data.arr.length = 0;
            codeXm.reset();
            descXm.reset();
        }

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

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

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

        window.importMaterial = function (data) {
            console.log(data);
            data = data.materialList;
            var html = "";
            for (var i = 0; i < data.length; i++) {
                html += "<tr data-id=" + data[i].materialId + ">";
                html += '<td>' + (i + 1) + '</td>';
                html += '<td>' + data[i].code + '</td>';
                html += '<td>' + data[i].type + '</td>';
                html += '<td>' + data[i].materialGroup + '</td>';
                html += '<td>' + data[i].unit + '</td>';
                html += '<td>' + data[i].description + '</td>';
                html += '<td class="amount">' + data[i].amount + '</td>';
                html += '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>';
                html += "</tr>";
            }

            $('#materialTable').empty().append(html);
        }


        $('#importPlan').click(function () {
            parent.layer.open({
                title: '导入物料',
                type: 2,
                area: ['550px', '300px'],
                content: '${ctx}/inventory/toImportMaterialForm'
            });
        });

        var saveFlag = true;
        form.on('submit(confirm)', function (data) {
            if (!saveFlag) {
                return;
            }
            var bom = {};
            bom.id = '${order.id}';
            bom.inWarehouseId = data.field.inWarehouseId;
            bom.outWarehouseId = data.field.outWarehouseId;
            bom.remarks = data.field.remarks;
            var arr = [];
            var $trs = $('#materialTable>tr');
            for (var i = 0; i < $trs.length; i++) {
                var $tr = $trs.eq(i);
                var material = {};
                material.materialId = $tr.attr("data-id");
                material.amount = $tr.find('td.amount').text();
                if(isBlank(material.amount)){
                    material.amount = $tr.find('td').eq(6).find("input").val();
                }
                arr.push(material);
                if (!/^\d+(\.\d{1,2})?$/.test(material.amount)) {
                    layer.msg('第' + (i + 1) + '行下单数量格式不正确');
                    return;
                }
                if (Number(material.amount) <= 0) {
                    layer.msg('第' + (i + 1) + '行下单数量需大于0');
                    return;
                }
            }
            bom.details = arr;
            saveFlag = false;
            $.ajax({
                url: '${ctx}/material/order/addSupplyOrder',
                method: 'post',
                contentType: 'application/json',
                data: JSON.stringify(bom),
                dataType: 'JSON',
                success: function (res) {
                    afterSuccess(res);
                },
                complete: function () {
                    saveFlag = true;
                }
            });
        });


        $(document).on('click', '.hx_del', function () {
            $(this).parent('li').remove();
        });

    })

    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>

