<%--
  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>
        <a id="editAll" class="btn btn-primary btn-sm" onclick="addReceiver('#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(materialRequisition.materialRequisitionInfoList)};
        $(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: 'receiver.name',
                    title: '领用人',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#receiverTpl").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('');
                    }
                }
            ]
        });
        $(selector).on('check.bs.table uncheck.bs.table load-success.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            $('#editAll').prop('disabled', !getSelections().length);
        });
    }

    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 addReceiver() {

        if (!$("#officeId").val()) {
            jp.warning('请选择领用机构！');
            return;
        }

        if(!getSelections().length){
            jp.warning('请添加并勾选明细!');
            return;
        }

        jp.openGridSelectDialog({
            title: '选择领用人',
            isMultiSelect: false,
            url: "${ctx}/sys/user/list?office.id=" + $("#officeId").val(),
            fieldLabels: "领用人|手机|归属公司|归属部门",
            fieldKeys: "name|phone|company.name|office.name",
            searchLabels: "领用人",
            searchKeys: "name",

        }, function (items) {
            var receiver = items[0];
            // TODO: 获取选中的明细下标
            getSelections().forEach(function (item) {
                var index = getTableData().findIndex(function (current) {
                    return current.ledgerInfo.id === item.ledgerInfo.id;
                })
                updateRow(index, {
                    receiver: receiver
                })
            })

        })
    }

    /**
     * 点击扫码显示扫码窗口
     */
    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="materialRequisitionInfoList{{idx}}_id" name="materialRequisitionInfoList[{{idx}}].id" type="hidden"
           value="{{row.id}}"/>
    <input id="materialRequisitionInfoList{{idx}}_delFlag" name="materialRequisitionInfoList[{{idx}}].delFlag"
           type="hidden" value="{{row.delFlag}}"/>
    <input id="materialRequisitionInfoList{{idx}}_materialRequisition"
           name="materialRequisitionInfoList[{{idx}}].materialRequisition.id" type="hidden"
           value="{{row.materialRequisition.id}}"/>
    <input id="materialRequisitionInfoList{{idx}}_ledgerInfoId"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.id" type="hidden" value="{{row.ledgerInfo.id}}"/>
</script>

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

<script id="ledgerInfoTypeTpl" type="text/html">//<!--
    <sys:treeselect id="materialRequisitionInfoList{{idx}}_ledgerInfoType" name="materialRequisitionInfoList[{{idx}}].ledgerInfo.type.id" value="{{row.ledgerInfo.type.id}}" labelName="materialRequisitionInfoList{{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="materialRequisitionInfoList{{idx}}_ledgerInfoModel"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.model" type="text" class="form-control" readonly
           value="{{row.ledgerInfo.model}}"/>
</script>
<script id="ledgerInfoAmountTpl" type="text/html">
    <input id="materialRequisitionInfoList{{idx}}_ledgerInfoAmount"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.amount" type="text" readonly class="form-control"
           value="{{row.ledgerInfo.amount}}"/>
</script>
<script id="receiverTpl" type="text/html">//<!--
  <sys:gridselect url="${ctx}/sys/user/list" id="materialRequisitionInfoList{{idx}}_receiver" name="materialRequisitionInfoList[{{idx}}].receiver.id" value="{{row.receiver.id}}" labelName="materialRequisitionInfoList[{{idx}}].receiver.name" labelValue="{{row.receiver.name}}"
                  title="选择领用人" cssClass="form-control required" fieldLabels="领用人|手机|归属公司|归属部门" iframeUrl="/warehouse/materialrequisition/materialRequisition/form" validate="true" callback="onSelectReceiver" validateSelector="#officeId" validateMsg="请选择领用机构" fieldKeys="name|phone|company.name|office.name" searchLabels="领用人" searchKeys="name" ></sys:gridselect>//-->
</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>