<%--
  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="addShelve('#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";

    console.log(${fns:toJson(storage)})

    function initTable(){
        var data = ${fns:toJson(storage.storageInfoList)};
        if(data.length){
            data = data.map(function(item){
                item.delFlag = 0;
                item.readonly = item.qrCode && item.qrCode.state === '2';
                item.infoSum = new Big(item.num).times(item.amount).toNumber();
                item.shelvesNames = item.shelvesList.map(function (e) {
                    return e.name;
                }).join(',');
                item.warehouseNames = item.warehouseList.map(function (e) {
                    return e.name;
                }).join(',');
                return item;
            })
        }
        $(selector).bootstrapTable({
            data: data,
            //是否显示分页（*）
            pagination: true,
            //排序方式
            sortOrder: "asc",
            //初始化加载第一页，默认第一页
            pageNumber:1,
            //每页的记录行数（*）
            pageSize: 10,
            sidePagination: "client",
            columns:[{checkbox: true, formatter: function(vlaue,row){return {disabled:  row.qrCode && row.qrCode.state === '2' }}},
                {
                    field: 'no',
                    title: '序号',
                    align: 'center',
                    width: 60,
                    formatter: function (value, row, index){
                        return '<span>'+(index+1)+'</span>'
                    }
                },
                {
                    field: 'type.name',
                    title: '品名',
                    formatter: function (value,row,index){
                        return Mustache.render($("#typeNameTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'type.code',
                    title: '代码',
                    formatter: function (value,row,index){
                        return Mustache.render($("#typeCodeTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'amount',
                    title: '单价',
                    formatter: function (value,row,index){
                        return Mustache.render($("#amountTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'type.unit',
                    title: '单位',
                    formatter: function (value,row,index){
                        return Mustache.render($("#unitTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'model',
                    title: '型号',
                    formatter: function (value,row,index){
                        return Mustache.render($("#modelTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'num',
                    title: '数量',
                    formatter: function (value,row,index){
                        return Mustache.render($("#numTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'infoSum',
                    title: '总价',
                    formatter: function (value,row,index){
                        return Mustache.render($("#infoSumTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'shelves',
                    title: '货架',
                    formatter: function (value,row,index){
                        return Mustache.render($("#shelvesTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'warehouse.name',
                    title: '仓库',
                    formatter: function (value,row,index){
                        return Mustache.render($("#warehouseTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'qrCode.state',
                    title: '&nbsp;&nbsp;状态&nbsp;&nbsp;',
                    formatter: function (value,row,index){
                        if(value === '1'){
                            return '已入库未入账'
                        }else if(value === '2'){
                            return '已入账未下账'
                        } else if(value === '3'){
                            return '已下账'
                        } else {
                            return '未入库'
                        }
                    }
                },
                {
                    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.qrCode && row.qrCode.state === '2') 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');
    }

    top.selectStorageData = function (res) {
        res.rows = res.rows.map(function (e) {
            return {
                ...e,
                infoSum: new Big(e.num).times(e.amount).toNumber()
            }
        })
        return res;
    }

    /**
     * 手动添加明细
     * @param selector
     */
    function addDetail(selector){
        // 选择该批次号下的货品明细
        if(!$("#batchNum").val()){
            jp.warning('请选择批次号！');
            return;
        }
        jp.openStorageSelectDialog({batchNum:$("#batchNum").val(),state: 0, isMultiSelect: true, gridSelectTableDataHandleName: 'selectStorageData' },function (items){
            if(Array.isArray(items)){
                /***
                 * 重复的物资编码去重
                 */
                var newItems = [];
                items.forEach(function(item){
                    var fined = getTableData().find(function(v){
                        return v.qrCode.id === item.qrCode.id
                    });
                    if(!fined){
                        newItems.push(item)
                    }else{
                        jp.warning('有物资重复不能入库！');
                    }
                })
                var data = newItems.map(function (item){
                    item[0] = false;
                    if(item.goodsInfo && !item.goodsInfo.amount){
                        item.goodsInfo.amount = 0;
                    }
                    return {
                        id: '',
                        delFlag: 0,
                        remarks: '',
                        ...item,
                        infoSum: new Big(item.num).times(item.amount).toNumber()
                    }
                });
                $(selector).bootstrapTable('append', data)
            }
        })
    }

    /**
     * 删除明细
     * @param index
     * @param rowId
     * @param rowDelFlag
     */
    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]
            })
        }
    }

    /**
     * 更新行
     * @param index 下标
     * @param row  更新对象
     */
    function updateRow(index, row){
        $(selector).bootstrapTable('updateRow', {
            index: index,
            row: row
        })
    }

    /**
     * 监听input值，并更新行
     * @param rowIndex 更新行的下标
     * @param elem  元素
     * @param field 属性
     */
    function onInputChange(rowIndex, elem , field){
        var obj = {};
        obj[field] = $(elem).val()
        var timer = null;
        clearTimeout(timer);
        timer = setTimeout(function (){
            updateRow(rowIndex, obj)
        }, 0)
    }

    /**
     * 监听类型选择回调并更新行
     * @param nodes 选中数据
     * @param rowIndex 行下标
     */
    function onSelectType(nodes, rowIndex){
        if(Array.isArray(nodes) && nodes.length === 1){
            var node = nodes[0];
            var obj = {
                type: {
                    id: node.id,
                    name: node.text
                }
            };
            updateRow(rowIndex, obj)
        }
    }

    function onSelectShelves(nodes, rowIndex){
        if(Array.isArray(nodes)){
            var obj = {
                shelvesIds: '',
                warehouseIds: '',
                shelvesNames: '',
                warehouseNames: ''
            };
            var warehouseIdMap = {};
            nodes.forEach(function (item) {
                obj.shelvesIds += item.id + ',';
                obj.shelvesNames += item.name + ',';
                if (!warehouseIdMap[item.warehouse.id]) {
                    obj.warehouseIds += item.warehouse.id + ',';
                    obj.warehouseNames += item.warehouse.name + ',';
                    warehouseIdMap[item.warehouse.id] = true;
                }
            })
            // var node = nodes[0];
            // var obj = {
            //     shelves: {
            //         id: node.id,
            //         name: node.name
            //     },
            //     warehouse: node.warehouse
            // };
            updateRow(rowIndex, obj)
        }
    }

    /**
     * 获取所有明细数据
     * @returns {*|jQuery}
     */
    function getTableData(useCurrentPage){
        return $(selector).bootstrapTable('getData',{
            useCurrentPage: useCurrentPage
        });
    }

    /**
     * 批量添加货架
     */
    function addShelve(){
        jp.openShelvesSelectDialog(function (items){
            setTimeout(function(){
                // var Shelve = items[0]; // 货架对象

                var obj = {
                    shelvesIds: '',
                    warehouseIds: '',
                    shelvesNames: '',
                    warehouseNames: ''
                };
                var warehouseIdMap = {};
                items.forEach(function (item) {
                    obj.shelvesIds += item.id + ',';
                    obj.shelvesNames += item.name + ',';
                    if (!warehouseIdMap[item.warehouse.id]) {
                        obj.warehouseIds += item.warehouse.id + ',';
                        obj.warehouseNames += item.warehouse.name + ',';
                        warehouseIdMap[item.warehouse.id] = true;
                    }
                })

                var realSelections = []; // 保存真实选中的数据
                var allSelections = getSelections(); // 保存所有选中的数据（含分页）
                var currentPageData = getTableData(true); // 保存当前分页数据
                allSelections.forEach(function(item){
                    var finded = currentPageData.find(function(value){
                        return value.qrCode.id === item.qrCode.id
                    });
                    if(finded){
                        realSelections.push(item);
                    }
                });
                realSelections.forEach(function (item){
                    var index = getTableData().findIndex(function (current){
                        return current.qrCode.id === item.qrCode.id;
                    }); // 需更新的行的下标
                    // updateRow(index,{
                    //     shelves: {
                    //         id: Shelve.id,
                    //         name: Shelve.name
                    //     },
                    //     warehouse: Shelve.warehouse
                    // })
                    updateRow(index, Object.assign({}, obj));
                })
            },200)

        }, true);
    }

    function updateTask(allList, count, updateCallback){
        var list = allList.slice(0, count);
        list.forEach(function (item){
            var index = getTableData().findIndex(function (current){
                return current.qrCode.id === item.qrCode.id;
            }); // 需更新的行的下标
            updateCallback(index);
        });
        setTimeout(function(){
            var newList = allList.slice(count);
            if(newList.length > 0){
                updateTask(newList,count,updateCallback);
            }
        },300)
    }

    /**
     * 点击扫码显示扫码窗口
     */
    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){
        // console.log($(elem).val());
        try{
            var json = JSON.parse($(elem).val());
            var qrCodeId = json.code;
            var goodsInfoId = json.infoId;
            jp.get('${ctx}/warehouse/goods/goods/getGIAndQCByTwoId?goodsInfoId='+goodsInfoId+"&qrCodeId="+qrCodeId, function (res){
                var qrCode = res.body.qrCode;
                var fined = getTableData().find(function(v){
                    return v.qrCode.id === qrCode.id
                });
                if(fined){
                    jp.warning('有物资重复不能入库!');
                    return;
                }
                $(selector).bootstrapTable('append',[
                    {
                        qrCode: qrCode,
                        goodsInfo: qrCode.goodsInfo,
                        ...qrCode.goodsInfo,
                        id: '',
                        delFlag: 0,
                        remarks: ''
                    }
                ]);
                $(elem).val('').focus();
            })

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

<script id="hideTpl" type="text/html">
    <input name="storageInfoList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
    <input  name="storageInfoList[{{idx}}].delFlag" type="hidden" value="{{row.delFlag}}"/>
    <input  name="storageInfoList[{{idx}}].goodsInfo.id" type="hidden" value="{{row.goodsInfo.id}}"/>
    <input  name="storageInfoList[{{idx}}].goodsInfo.name" type="hidden" value="{{row.goodsInfo.name}}"/>
    <input  name="storageInfoList[{{idx}}].goodsInfo.amount" type="hidden" value="{{row.goodsInfo.amount}}"/>
    <input  name="storageInfoList[{{idx}}].warehouse.id" type="hidden" value="{{row.warehouse.id}}" readonly class="form-control" />
    <input  name="storageInfoList[{{idx}}].warehouse.name" type="hidden" value="{{row.warehouse.name}}" readonly class="form-control" />
    <input  name="storageInfoList[{{idx}}].amount" type="hidden" value="{{row.amount}}" readonly class="form-control" />
    <input  name="storageInfoList[{{idx}}].qrCode.id" type="hidden" value="{{row.qrCode.id}}" readonly class="form-control" />
    <input name="storageInfoList[{{idx}}].name" type="hidden" readonly value="{{row.name}}"  class="form-control "/>
    <input name="storageInfoList[{{idx}}].type.id" type="hidden" readonly value="{{row.type.id}}"  class="form-control "/>
    <input name="storageInfoList[{{idx}}].type.name" type="hidden" readonly value="{{row.type.name}}"  class="form-control "/>
    <input name="storageInfoList[{{idx}}].model" type="hidden" readonly value="{{row.model}}"  class="form-control "/>
    <input name="storageInfoList[{{idx}}].shelves.id" type="hidden" readonly value="{{row.shelves.id}}"  class="form-control "/>
    <input name="storageInfoList[{{idx}}].shelves.name" type="hidden" readonly value="{{row.shelves.name}}"  class="form-control "/>
    <input name="storageInfoList[{{idx}}].remarks" type="hidden" readonly value="{{row.remarks}}"  class="form-control "/>
</script>

<script id="nameTpl" type="text/html">
    <input  type="text" readonly value="{{row.name}}"  class="form-control "/>
</script>
<script id="typeNameTpl" type="text/html">//<!--
    {{#row.readonly}}
        <sys:treeselectNotNameProperty id="storageInfoList{{idx}}_typeName" name="storageInfoList[{{idx}}].type.id" value="{{row.type.id}}"
                                           labelName="storageInfoList[{{idx}}].type.name" labelValue="{{row.type.name}}"
                                           title="品名代码" url="/warehouse/materialtype/materialType/treeData" notAllowSelectParent="true"
                                           cssClass="form-control required" disabled="disabled" allowClear="false" allowSearch="true" callback="onSelectType"  />
    {{/row.readonly}}
  {{^row.readonly}}
        <sys:treeselectNotNameProperty id="storageInfoList{{idx}}_typeName" name="storageInfoList[{{idx}}].type.id" value="{{row.type.id}}"
                                           labelName="storageInfoList[{{idx}}].type.name" labelValue="{{row.type.name}}"
                                           title="品名代码" url="/warehouse/materialtype/materialType/treeData" notAllowSelectParent="true"
                                           cssClass="form-control required" allowClear="false" allowSearch="true" callback="onSelectType"  />
  {{/row.readonly}}
    //-->
</script>
<script id="typeCodeTpl" type="text/html">
    <input id="storageInfoList{{idx}}_typeCode" name="storageInfoList[{{idx}}].type.code" type="text" value="{{row.type.code}}" readonly class="form-control required"/>
</script>
<script id="typeTpl" type="text/html">//<!--
    <sys:treeselectNotNameProperty id="storageInfoList{{idx}}_type" name="storageInfoList[{{idx}}].type.id" value="{{row.type.id}}" labelName="storageInfoList{{idx}}.type.name" labelValue="{{row.type.name}}"
							title="品名代码" url="/warehouse/materialtype/materialType/treeData" cssClass="form-control  " disabled="disabled" allowClear="true" allowSearch="true" callback="onSelectType" />//-->
</script>
<script id="amountTpl" type="text/html">
    <input id="storageInfoList{{idx}}_amount" name="storageInfoList[{{idx}}].amount" type="text" value="{{row.amount}}" readonly onchange="onInputChange('{{idx}}', this, 'amount')"  class="form-control required"/>
</script>
<script id="unitTpl" type="text/html">
    <input id="storageInfoList{{idx}}_unit" name="storageInfoList[{{idx}}].type.unit" type="text" value="{{row.type.unit}}" readonly onchange="onInputChange('{{idx}}', this, 'type.unit')"  class="form-control required"/>
</script>
<script id="modelTpl" type="text/html">
    <input id="storageInfoList{{idx}}_model"  type="text" value="{{row.model}}" readonly onchange="onInputChange('{{idx}}', this, 'model')"    class="form-control "/>
</script>
<script id="numTpl" type="text/html">
    <input id="storageInfoList{{idx}}_num" name="storageInfoList[{{idx}}].num" readonly type="text" value="{{row.num}}" onchange="onInputChange('{{idx}}', this, 'num')"  class="form-control required"/>
</script>

<script id="infoSumTpl" type="text/html">
    <input id="storageInfoList{{idx}}_infoSum" name="storageInfoList[{{idx}}].infoSum" type="text" value="{{row.infoSum}}" readonly onchange="onInputChange('{{idx}}', this, 'infoSum')"  class="form-control required"/>
</script>
<script id="shelvesTpl" type="text/html">//<!--
  {{#row.readonly}}
  <sys:shelvesselectNotName id="storageInfoList{{idx}}_shelves" name="storageInfoList[{{idx}}].shelvesIds" value="{{row.shelvesIds}}" labelName="storageInfoList[{{idx}}].shelvesNames" labelValue="{{row.shelvesNames}}"
                   cssClass="form-control required" iframeUrl="/warehouse/storage/storage/form" disabled="disabled" isMultiSelected="true" allowClear="false" />
  {{/row.readonly}}
  {{^row.readonly}}
  <sys:shelvesselectNotName id="storageInfoList{{idx}}_shelves" name="storageInfoList[{{idx}}].shelvesIds" value="{{row.shelvesIds}}" labelName="storageInfoList[{{idx}}].shelvesNames" labelValue="{{row.shelvesNames}}"
                     cssClass="form-control required" iframeUrl="/warehouse/storage/storage/form" callback="onSelectShelves" isMultiSelected="true" allowClear="false" />//-->
{{/row.readonly}}
</script>
<script id="remarksTpl" type="text/html">
    {{#row.readonly}}
    <textarea id="storageInfoList{{idx}}_remarks"  rows="2"  readonly class="form-control ">{{row.remarks}}</textarea>
    {{/row.readonly}}
    {{^row.readonly}}
    <textarea id="storageInfoList{{idx}}_remarks" rows="2"  onchange="onInputChange('{{idx}}', this, 'remarks')"  class="form-control ">{{row.remarks}}</textarea>
    {{/row.readonly}}
</script>
<script id="warehouseTpl" type="text/html">
    <input id="storageInfoList{{idx}}_warehouseName"  type="text" value="{{row.warehouseNames}}" readonly  class="form-control "/>
    <input id="storageInfoList{{idx}}_warehouseIds" name="storageInfoList[{{idx}}].warehouseIds"  type="hidden" value="{{row.warehouseIds}}" readonly  class="form-control "/>
    <input type="hidden" id="storageInfoList{{idx}}_shelvesIds" name="storageInfoList[{{idx}}].shelvesIds" value="{{row.shelvesIds}}">
</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" style="ime-mode: active" onchange="onScanChange(this)">
                <span class="text-danger">请切换英文输入法</span>
            </div>
        </div>
    </div>
    <br>
</script>
