<%--
  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'}">
        <button type="button" class="btn btn-primary btn-sm" onclick="addDetail('#detail_table')" title="新增"><i class="fa fa-plus"></i>
            手动添加</button>
        <button type="button" class="btn btn-primary btn-sm" onclick="addScan('#detail_table')" title="新增"><i class="fa fa-plus"></i>
            扫码添加</button>
        <button id="editAll" type="button" class="btn btn-primary btn-sm" disabled onclick="addReceiver()" title="新增"><i
                class="fa fa-plus"></i> 批量编辑领用人</button>
    </c:if>
</div>
<table id="detail_table" data-toolbar="#toolbar"></table>
<script>
    var selector = "#detail_table";

    function initTable() {
        var data = ${fns:toJson(materialRequisition.materialRequisitionInfoList)};
        if(data.length){
            data = data.map(function(item){
                item.delFlag = 0;
                return item;
            })
        }
        $(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: '领用人',
                    align: 'center',
                    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 newItems = [];
                items.forEach(function(item){
                    var fined = getTableData().find(function(v){
                        return v.ledgerInfo.code === item.code
                    })
                    if(!fined){
                        newItems.push(item);
                    }else{
                        jp.warning('有物资重复不能领用！');
                    }
                })
                var data = newItems.map(function (item) {
                    item[0] = false;
                    return {
                        id: '',
                        delFlag: 0,
                        remarks: '',
                        ledgerInfo: item
                    }
                })
                $(selector).bootstrapTable('append', data)
            }
        })
    }

    function removeRow(index, rowId, rowDelFlag) {
        if (rowId && rowId != 'undefined') {
            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(ledgerInfoId) {

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

        layer.open({
            type: 1,
            title: '签名',
            auto:true,
            area:[800,600],
            content: '<div id="signBox" class="sign" contentEditable="true" style="width: 100%;height: 100%;"></div>',
            success: function (layero){
                $(layero[0]).find("#signBox").focus();
            },
            btn: ['确认','清空','取消'],
            btn1: function(index, layero){
                if(ledgerInfoId){
                    var i = getTableData().findIndex(function (current) {
                        return current.ledgerInfo.id === ledgerInfoId;
                    })
                    updateRow(i, {
                        receiver: $(layero[0]).find("#signBox img").attr('src')
                    })
                }else{
                    getSelections().forEach(function (item) {
                        var index = getTableData().findIndex(function (current) {
                            return current.ledgerInfo.id === item.ledgerInfo.id;
                        })
                        updateRow(index, {
                            receiver: $(layero[0]).find("#signBox img").attr('src')
                        })
                    });
                }
                layer.close(index);
            },
            btn2: function (index, layero){
                $(layero[0]).find("#signBox").empty().focus();
                return false;
            }
        })
    }

    /**
     * 点击扫码显示扫码窗口
     */
    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];

                    /***
                     * 重复的物资编码去重
                     */
                    var fined = getTableData().find(function(v){
                        return v.ledgerInfo.code === item.code
                    })
                    if(fined){
                        jp.warning('有物资重复不能领用');
                        return;
                    }
                    $(selector).bootstrapTable('append', [
                        {
                            id: '',
                            delFlag: 0,
                            remarks: '',
                            ledgerInfo: item
                        }
                    ]);
                    $(elem).val('').focus();
                }else{
                    jp.warning('未找到任何数据!');
                    $(elem).val('').focus();
                }
            })

        } catch (e) {
            console.log(e);
        }
    }

    function delSign(elem, index){
        $(elem).parent().remove();
        updateRow(index,{
            receiver: ''
        })
    }
</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">
    <input type="hidden" name="materialRequisitionInfoList[{{idx}}].receiver" value="{{row.receiver}}">
    {{#row.receiver}}
     <div class="sign-result">
         <img src="{{row.receiver}}" alt="签名" width="100%"  />
         <span class="del-sign" onclick="delSign(this, {{idx}})">&times;</span>
     </div>
    {{/row.receiver}}
    {{^row.receiver}}
    <a onclick="addReceiver('{{row.ledgerInfo.id}}')">签名</a>
    {{/row.receiver}}
</script>
<script id="remarksTpl" type="text/html">
    <textarea id="materialRequisitionInfoList{{idx}}_remarks" name="materialRequisitionInfoList[{{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>