<%--
  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 info = ${fns:toJson(materialRequisition)};
        console.log(info)
        var data = ${fns:toJson(materialRequisition.materialRequisitionInfoList)};
        if(data.length){
            data = data.map(function(item){
                item.delFlag = 0;
                item.canUse = info.status !== '2';
                item.remarks = jp.escapeHtml(item.remarks);
                item.infoSum = new Big(item.ledgerInfo.num).times(item.ledgerInfo.amount).toNumber();
                return item;
            })
        }
        $(selector).bootstrapTable({
            data: data,
            uniqueId: 'sortId',
            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.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.type.code',
                    title: '代码',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoTypeCodeTpl").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: "ledgerInfo.type.unit",
                    title: '单位',
                    formatter: function (value, row, index) {
                        return Mustache.render($("#ledgerInfoTypeUnitTpl").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: 'num',
                //     title: '数量',
                //     formatter: function (value, row, index) {
                //         return Mustache.render($("#ledgerInfoNumTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""), {
                //             row: row,
                //             idx: index
                //         })
                //     }
                // },
                // {
                //     field: 'infoSum',
                //     title: '总价',
                //     sortName: 'infoSum',
                //     formatter: function (value, row, index) {
                //         return Mustache.render($("#ledgerInfoInfoSumTpl").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) {
                        if (!row.canUse) return '';
                        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');
    }


    var addDetailColumns = {
        label: '物资编码|品名|代码|型号|批次号|单价|单位|数量|选择数量',
        key: 'code|type.name|type.code|model|batchNum|amount|type.unit|num|selectNum'
    };
    /**
     * 手动添加明细
     * @param selector
     */
    function addDetail(selector) {
        jp.openGridSelectDialog({
            title: '选择物资台账明细',
            isMultiSelect: true,
            url: "${ctx}/warehouse/ledger/ledger/findByQrOrCode",
            fieldLabels: addDetailColumns.label,
            fieldKeys: addDetailColumns.key,
            searchLabels: "物资编码",
            searchKeys: "code",
        }, function (items) {
            if (Array.isArray(items)) {
                if (items.some(function (e) {
                    return !e.selectNum;
                })) {
                    jp.alert('选择的数据必须填写选择数量');
                    return false;
                }
                /***
                 * 重复的物资编码去重
                 */
                // 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;
                //     item.infoSum = new Big(item.num).times(item.amount).toNumber();
                //     return {
                //         id: '',
                //         delFlag: 0,
                //         remarks: '',
                //         ledgerInfo: item,
                //         sortId: item.code
                //     }
                // })
                // $(selector).bootstrapTable('append', data)
                selectDetailHandle($(selector), items);
            }
        })
    }

    function selectDetailHandle (table, list) {
        var tableData = getTableData();
        var newTableData = tableData.slice();
        if (!tableData.length) {
            list.forEach(function (item) {
                var selectNum = Number(item.selectNum);
                var list = new Array(selectNum).fill(0).map(function (t, index) {
                    return {
                        id: '',
                        delFlag: 0,
                        remarks: '',
                        ledgerInfo: Object.assign({}, item),
                        sortId: item.code + '_' + index,
                        canUse: true
                    }
                })
                newTableData = newTableData.concat(list);
            })
        } else {
            list.forEach(function (item) {
                var list = tableData.filter(function (e) { return e.ledgerInfo.code === item.code });
                var selectNum = Number(item.selectNum);
                var length = list.length;
                var startIndex = newTableData.findIndex(function (e) { return e.ledgerInfo.code === item.code; });
                var endIndex = startIndex + length - 1;
                if (length > selectNum) {
                    var delNum = length - selectNum;
                    var delStartIndex = startIndex + selectNum;
                    newTableData.splice(delStartIndex, delNum);
                } else if (length < selectNum) {
                    var newAddList = new Array(selectNum - length).fill(0).map(function (t, index) {
                        return {
                            id: '',
                            delFlag: 0,
                            remarks: '',
                            ledgerInfo: Object.assign({}, item),
                            sortId: item.code + '_' + index,
                            canUse: true
                        }
                    });
                    newTableData.splice.apply(newTableData, [endIndex, 0].concat(newAddList));
                } else if (length === 0) {
                    var newAddList = new Array(selectNum).fill(0).map(function (t, index) {
                        return {
                            id: '',
                            delFlag: 0,
                            remarks: '',
                            ledgerInfo: Object.assign({}, item),
                            sortId: item.code + '_' + index,
                            canUse: true
                        }
                    });
                    newTableData = newTableData.concat(newAddList);
                }
            })
        }
        table.bootstrapTable('load', newTableData);
    }

    function positiveInteger (v) {
        return /^[1-9]\d*$/.test(v)
    }

    top.gridSelectColumnFormatterMap = {
        selectNum: {
            formatter: function (val, row, index) {
                return "<input type='number' class='form-control selectNum'  />"
            },
            events: {
                'change .selectNum': function (e, v, r, i) {
                    var dom = e.target;
                    var selectNum = Number(dom.value);
                    var num = r.num;
                    if (!positiveInteger(selectNum)) {
                        jp.alert('只能输入正整数');
                        dom.value = '';
                        return;
                    } else if (selectNum > num) {
                        jp.alert('选择的数量不能大于总数量');
                        dom.value = '';
                        return;
                    }
                    r.selectNum = dom.value;
                }
            }
        }

    }

    window.onbeforeunload = function () {
        delete top.gridSelectColumnFormatterMap;
    }

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

        jp.open({
            type: 2,
            title: '签名',
            auto:true,
            area:[800,600],
            content: '${ctx}/warehouse/materialrequisition/materialRequisition/writeSign',
            // success: function (layero){
            //     $(layero[0]).find("#signBox").focus();
            //     getDevice();
            // },
            btn: ['确认','取消'],
            btn1: function (index, layero) {
                var iframe = layero.find("iframe")[0].contentWindow;
                var img = iframe.getImg();
                if (!img) {
                    jp.close(index);
                    jp.message('请签字');
                    return;
                }
                if (ledgerInfoId) {
                    var i = getTableData().findIndex(function (current) {
                        return current.ledgerInfo.id === ledgerInfoId;
                    })
                    updateRow(i, {
                        receiver: img
                    })
                } else {
                    getSelections().forEach(function (item) {
                        var index = getTableData().findIndex(function (current) {
                            return item.sortId ? item.sortId === current.sortId : item.id === current.id;
                        })
                        updateRow(index, {
                            receiver: img
                        })
                    });
                }
                jp.close(index);
            },
            btn2: function (index, layero){
                var iframe = layero.find("iframe")[0].contentWindow;
                iframe.unload();
                jp.close(index);
            },
            cancel (i, layero) {
                var iframe = layero.find("iframe")[0].contentWindow;
                iframe.unload();
            }
        })
    }

    /**
     * 点击扫码显示扫码窗口
     */
    function addScan() {
        layer.open({
            type: 1,
            title: '扫码',
            auto: true,
            area: ['1200', '600'],
            content: $("#scanTpl").html(),
            btn: ['确定', '关闭'],
            success: function (layer) {
                // $("#scanResult").focus();
                scanStart();
                renderScanTable();
                setTimeout(function () {
                    // var width = layer.width();
                    var height = layer.height();
                    layer.find('.layui-layer-content').height(height - 97);
                })
            },
            yes: function (index, layero) {
                var selectTableData = getSelectScanTable();
                if (!selectTableData.length) {
                    jp.alert('至少选择一条数据');
                    return;
                }
                if (selectTableData.some(function (e) {
                    return !e.selectNum;
                })) {
                    jp.alert('选择的数据必须填写选择数量');
                    return false;
                }
                scanStop();
                selectDetailHandle($(selector), selectTableData);
                layer.close(index);
            },
            btn2: function () {
                scanStop();
            },
            cancel: function () {
                scanStop();
            }
        })
    }

    function scanIptChangeCallback (val) {
        var json = JSON.parse(val);
        var qrCodeId = json.code;
        // var params = "qrId=" + json.code;
        jp.get('${ctx}/warehouse/ledger/ledger/findByQrOrCode?qrId=' + qrCodeId, function (res) {
            var data = res.rows || [];
            if (data.length) {
                var item = data[0];
                if (!item) {
                    jp.warning('不是有效的二维码');
                    return;
                }
                //
                // /***
                //  * 重复的物资编码去重
                //  */
                var fined = getSelectScanTable().find(function(v){
                    return v.ledgerInfo.code === item.code
                })
                if(fined){
                    jp.warning('有物资重复不能领用');
                    return;
                }
                getScanTable().bootstrapTable('append', item);
                // $(elem).val('').focus();
                console.log(data)
            }else{
                jp.warning('未找到任何数据!');
                // $(elem).val('').focus();
            }
        })
    }

    function getScanTable () {
        return $("#scan_detail_table");
    }

    function getSelectScanTable () {
        return getScanTable().bootstrapTable('getSelections');
    }

    function renderScanTable () {
        var table = getScanTable();
        var labelList = addDetailColumns.label.split('|');
        var keyList = addDetailColumns.key.split('|');
        table.bootstrapTable('destroy').bootstrapTable({
            data: [],
            columns: [
                { checkbox: true }
            ].concat(
                labelList.map(function (el, index) {
                    var key = keyList[index];
                    return {
                        title: el,
                        field: keyList[index],
                        formatter (v, r, i) {
                            var result = v;
                            if (top.gridSelectColumnFormatterMap[key]) {
                                result = top.gridSelectColumnFormatterMap[key].formatter(v, r, i)
                            }
                            return result;
                        },
                        events: top.gridSelectColumnFormatterMap[key] ? top.gridSelectColumnFormatterMap[key].events : {}
                    }
                })
            )
        })
    }

    /**
     * 扫码
     * 一、获取扫码结果
     * 二、请求后台接口获取结果
     * 三、增一条明细数据
     * 四、清空扫码结果
     * @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: ''
        })
    }

    function viewImage (u) {
        jp.showPic(u);
    }
</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="ledgerInfoTypeCodeTpl" type="text/html">
    <input id="materialRequisitionInfoList{{idx}}_ledgerInfoTypeCode"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.type.code" type="text" class="form-control" readonly
           value="{{row.ledgerInfo.type.code}}"/>
</script>
<script id="ledgerInfoTypeUnitTpl" type="text/html">
    <input id="materialRequisitionInfoList{{idx}}_ledgerInfoTypeUnit"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.type.unit" type="text" class="form-control" readonly
           value="{{row.ledgerInfo.type.unit}}"/>
</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="ledgerInfoNumTpl" type="text/html">
    <input id="materialRequisitionInfoList{{idx}}_ledgerInfoNum"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.num" type="text" readonly class="form-control"
           value="{{row.ledgerInfo.num}}"/>
</script>
<script id="ledgerInfoInfoSumTpl" type="text/html">
    <input id="materialRequisitionInfoList{{idx}}_ledgerInfoInfoSum"
           name="materialRequisitionInfoList[{{idx}}].ledgerInfo.infoSum" type="text" readonly class="form-control"
           value="{{row.ledgerInfo.infoSum}}"/>
</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%" onclick="viewImage('{{row.receiver}}')" />
         {{#row.canUse}}
            <span class="del-sign" onclick="delSign(this, '{{idx}}')">&times;</span>
         {{/row.canUse}}
     </div>
    {{/row.receiver}}
    {{^row.receiver}}
    <a onclick="addReceiver('{{row.ledgerInfo.id}}')">签名</a>
    {{/row.receiver}}
</script>
<script id="remarksTpl" type="text/html">
    {{#row.canUse}}
    <textarea id="materialRequisitionInfoList{{idx}}_remarks" name="materialRequisitionInfoList[{{idx}}].remarks" rows="2"
              onchange="onInputChange('{{idx}}', this, 'remarks')" class="form-control ">{{row.remarks}}</textarea>
    {{/row.canUse}}
    {{^row.canUse}}
    <textarea id="materialRequisitionInfoList{{idx}}_remarks" name="materialRequisitionInfoList[{{idx}}].remarks" rows="2"
              onchange="onInputChange('{{idx}}', this, 'remarks')" class="form-control " readonly>{{row.remarks}}</textarea>
    {{/row.canUse}}

</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>
