<%--
  Created by IntelliJ IDEA.
  User: yangzi
  Date: 2023/2/21
  Time: 10:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/webpage/include/taglib.jsp" %>
<div id="toolbar" class="text-left">
    <c:if test="${mode == 'add' || mode == 'edit'}">
        <a class="btn btn-primary btn-sm" onclick="addDetail('#detail_table')" title="新增"><i class="fa fa-plus"></i>
            手动添加</a>
        <a class="btn btn-primary btn-sm" onclick="addScan('#detail_table')" title="新增"><i class="fa fa-plus"></i>
            扫码添加</a>
    </c:if>
</div>
<table id="detail_table" data-toolbar="#toolbar"></table>
<script>
    var selector = "#detail_table";

    function initTable() {
        var data = ${fns:toJson(outbound.outboundInfoList)};
        $(selector).bootstrapTable({
            data: data,
            columns: [{checkbox: true},
                {
                    field: 'no',
                    title: '序号',
                    align: 'center',
                    width: 60,
                    formatter: function (value, row, index) {
                        var tpl = $("#hideTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, "");
                        var html = Mustache.render(tpl, {
                            idx: index,
                            row: row
                        })

                        return html + '<span>' + (index + 1) + '</span>'
                    }
                },
                {
                    field: 'ledgerInfo.name',
                    title: '物资名称',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoNameTpl").html(), {
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'ledgerInfo.code',
                    title: '物资编码',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoCodeTpl").html(), {
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'ledgerInfo.type.name',
                    title: '类型',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoTypeTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""), {
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'ledgerInfo.model',
                    title: '型号',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoModelTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""), {
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'ledgerInfo.amount',
                    title: '单价',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoAmountTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""), {
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'remarks',
                    title: '备注',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#remarksTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""), {
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: '',
                    title: '操作',
                    formatter: function (value, row, index) {
                        var text = row.delFlag == 1 ? '撤销删除' : '删除';
                        var result = ["<a href='javascript:void(0);' onclick=\"removeRow(" + index + ", '" + row.id + "',  '" + row.delFlag + "')\">" + text + "</a>"]
                        return result.join('');
                    }
                }
            ]
        });
    }

    function getSelections() {
        return $(selector).bootstrapTable('getSelections');
    }

    /**
     * 手动添加明细
     * @param selector
     */
    function addDetail(selector) {
        jp.openGridSelectDialog({
            title: '选择物资台账明细',
            isMultiSelect: true,
            url: "${ctx}/warehouse/ledger/ledger/findByQrOrCode",
            fieldLabels: "物资编码|物资名称|类型|型号|批次号|单价",
            fieldKeys: "code|name|type.name|model|batchNum|amount",
            searchLabels: "物资编码",
            searchKeys: "code",
        }, function (items) {
            if (Array.isArray(items)) {
                var data = items.map(function (item) {
                    item[0] = false;
                    return {
                        id: '',
                        delFlag: 0,
                        remarks: '',
                        ledgerInfo: item
                    }
                })
                $(selector).bootstrapTable('append', data)
            }
        })
    }

    function removeRow(index, rowId, rowDelFlag) {
        if (rowId) {
            var delFlag = rowDelFlag === 1 ? 0 : 1
            updateRow(index, {
                delFlag: delFlag
            })
        } else {
            $(selector).bootstrapTable("remove", {
                field: '$index',
                values: [index]
            })
        }
    }

    function updateRow(index, row) {
        $(selector).bootstrapTable('updateRow', {
            index: index,
            row: row
        })
    }

    function onInputChange(rowIndex, elem, field) {
        var obj = {};
        obj[field] = $(elem).val()
        var timer = null;
        clearTimeout(timer);
        timer = setTimeout(function () {
            updateRow(rowIndex, obj)
        }, 0)
    }

    function onSelectReceiver(nodes, rowIndex) {
        if (Array.isArray(nodes) && nodes.length === 1) {
            var node = nodes[0];
            var obj = {
                receiver: {
                    id: node.id,
                    name: node.name
                }
            };
            updateRow(rowIndex, obj)
        }
    }

    /**
     * 获取所有明细数据
     * @returns {*|jQuery}
     */
    function getTableData() {
        return $(selector).bootstrapTable('getData');
    }
    
    /**
     * 点击扫码显示扫码窗口
     */
    function addScan() {
        layer.open({
            type: 1,
            title: '扫码',
            auto: true,
            area: ['500', '300'],
            content: $("#scanResultTpl").html(),
            success: function () {
                $("#scanResult").focus();
            },
            btn: ['关闭']
        })
    }

    /**
     * 扫码
     * 一、获取扫码结果
     * 二、请求后台接口获取结果
     * 三、增一条明细数据
     * 四、清空扫码结果
     * @param elem
     */
    function onScanChange(elem) {
        try {
            var json = JSON.parse($(elem).val());
            var qrCodeId = json.code;
            jp.get('${ctx}/warehouse/ledger/ledger/findByQrOrCode?qrCodeId=' + qrCodeId, function (res) {
                var data = res.rows || [];
                if (data.length) {
                    var item = data[0];
                    $(selector).bootstrapTable('append', [
                        {
                            id: '',
                            delFlag: 0,
                            remarks: '',
                            ledgerInfo: item
                        }
                    ]);
                    $(elem).val('').focus();
                }else{
                    jp.warning('未找到任何数据!');
                    $(elem).val('').focus();
                }
            })

        } catch (e) {
            console.log(e);
        }
    }
</script>

<script id="hideTpl" type="text/html">
    <input id="outboundInfoList{{idx}}_id" name="outboundInfoList[{{idx}}].id" type="hidden"
           value="{{row.id}}"/>
    <input id="outboundInfoList{{idx}}_delFlag" name="outboundInfoList[{{idx}}].delFlag"
           type="hidden" value="{{row.delFlag}}"/>
    <input id="outboundInfoList{{idx}}_outbound"
           name="outboundInfoList[{{idx}}].outbound.id" type="hidden"
           value="{{row.outbound.id}}"/>
    <input id="outboundInfoList{{idx}}_ledgerInfoId"
           name="outboundInfoList[{{idx}}].ledgerInfo.id" type="hidden" value="{{row.ledgerInfo.id}}"/>
</script>

<script id="ledgerInfoNameTpl" type="text/html">
    <input id="outboundInfoList{{idx}}_ledgerInfoName" readonly
           name="outboundInfoList[{{idx}}].ledgerInfo.name" type="text" class="form-control"
           value="{{row.ledgerInfo.name}}"/>
</script>
<script id="ledgerInfoCodeTpl" type="text/html">
    <input id="outboundInfoList{{idx}}_ledgerInfoCode" readonly
           name="outboundInfoList[{{idx}}].ledgerInfo.code" type="text" class="form-control"
           value="{{row.ledgerInfo.code}}"/>
</script>

<script id="ledgerInfoTypeTpl" type="text/html">//<!--
    <sys:treeselect id="outboundInfoList{{idx}}_ledgerInfoType" name="outboundInfoList[{{idx}}].ledgerInfo.type.id" value="{{row.ledgerInfo.type.id}}" labelName="outboundInfoList{{idx}}.ledgerInfo.type.name" labelValue="{{row.ledgerInfo.type.name}}"
							title="类型" url="/warehouse/materialtype/materialType/treeData" cssClass="form-control  " disabled="disabled" allowClear="true"/>//-->
</script>
<script id="ledgerInfoModelTpl" type="text/html">
    <input id="outboundInfoList{{idx}}_ledgerInfoModel"
           name="outboundInfoList[{{idx}}].ledgerInfo.model" type="text" class="form-control" readonly
           value="{{row.ledgerInfo.model}}"/>
</script>
<script id="ledgerInfoAmountTpl" type="text/html">
    <input id="outboundInfoList{{idx}}_ledgerInfoAmount"
           name="outboundInfoList[{{idx}}].ledgerInfo.amount" type="text" readonly class="form-control"
           value="{{row.ledgerInfo.amount}}"/>
</script>

<script id="remarksTpl" type="text/html">
    <textarea id="storageInfoList{{idx}}_remarks" name="storageInfoList[{{idx}}].remarks" rows="2"
              onchange="onInputChange('{{idx}}', this, 'remarks')" class="form-control ">{{row.remarks}}</textarea>
</script>

<script id="scanResultTpl" type="text/html">
    <br>
    <div class="container-fluid">
        <div class="row">
            <div class="col-xs-2 text-right">
                <label>扫码结果:</label>
            </div>
            <div class="col-xs-10">
                <input type="text" id="scanResult" class="form-control" onchange="onScanChange(this)">
                <span class="text-danger">请切换英文输入法</span>
            </div>
        </div>
    </div>
    <br>
</script>