<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2023/2/28
  Time: 9:21
  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>--%>
        <button id="editAll" type="button" class="btn btn-primary btn-sm" disabled="true"  onclick="addShelve('#detail_table')" 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(profitWarehousing.profitWarehousingInfoList)};
        console.log(data)
        if(data.length){
            data = data.map(function(item){
                item.delFlag = 0;
                item.shelvesNames = item.shelvesList.map(function (e) { return e.name }).join(',') + ',';
                item.warehouseNames = item.warehouseList.map(function (e) { return e.name }).join(',') + ',';
                item.remarks = jp.escapeHtml(item.remarks);
                item.readonly = item.qrCode && Number(item.qrCode.state) > 0
                return item;
            })
        }
        $(selector).bootstrapTable({
            data: data,
            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){
                        var tpl = $("#hideTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, "");
                        var html = Mustache.render(tpl, {
                            idx: index,
                            row: row
                        })

                        return html + '<span>'+(index+1)+'</span>'
                    }
                },
                // {
                //     field: 'name',
                //     title: '名称',
                //     formatter: function (value,row,index){
                //         return Mustache.render($("#nameTpl").html(),{
                //             row: row,
                //             idx: index
                //         })
                //     }
                // },
                {
                    field: 'type.name',
                    title: '品名',
                    formatter: function (value,row,index){
                        return Mustache.render($("#typeTpl").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: 'marking',
                    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: 'shelvesIds',
                    title: '货架',
                    formatter: function (value,row,index){
                        return Mustache.render($("#shelvesTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'warehouseIds',
                    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 === '2'){
                            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 && Number(row.qrCode.state) > 0) 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');
    }

    /**
     * 删除明细
     * @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]
            })
        }
        setSumPrice();
    }

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

    /**
     * 监听input值，并更新行
     * @param rowIndex 更新行的下标
     * @param elem  元素
     * @param field 属性
     */
    // function onInputChange(rowIndex, elem , field){
    //     var obj = {};
    //     obj[field] = $(elem).val()
    //     updateRow(rowIndex, obj)
    //     if(field === 'amount' &&  obj[field]) {
    //         // 正则表达式验证可以带小数点的数字
    //         // 不是数字
    //         if(!/^(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(obj[field])) {
    //             jp.warning("输入正确的金额");
    //             $(elem).val('')
    //             return
    //         }
    //         setSumPrice();
    //     }
    // }
    function onInputChange(rowIndex, elem , field){
        var obj = {};
        obj[field] = $(elem).val();
        // 校验数量与单价
        if(field === 'num' &&  obj[field]){

            // 正则表达式验证可以带小数点的数字
            var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
            // 不是数字
            if(!reg.test(obj[field])){
                jp.warning("必须是数字");
                $(elem).val('')
                return
            }

            if (Number(obj[field]) <= 0) {
                jp.warning("数量不能小于等于0");
                $(elem).val('');
                return;
            }

            if ($("#profitWarehousingInfoList" + rowIndex + "_amount").val()) {
                obj.infoSum = new Big($("#profitWarehousingInfoList" + rowIndex + "_amount").val()).times(obj[field]).toNumber();
            }
        }

        if(field === 'amount' &&  obj[field]) {
            // 正则表达式验证可以带小数点的数字
            // 不是数字
            if(!/^(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(obj[field])) {
                jp.warning("输入正确的金额");
                $(elem).val('')
                return
            }

            if ($("#profitWarehousingInfoList" + rowIndex + "_num").val()) {
                obj.infoSum = new Big($("#profitWarehousingInfoList" + rowIndex + "_num").val()).times(obj[field]).toNumber();
            }
        }

        updateRow(rowIndex, obj);

        if((field === 'num' && obj[field]) || (field === 'amount' &&  obj[field])) {
            setSumPrice();
        }
    }

    // function setSumPrice(){
    //     var data = $(selector).bootstrapTable('getData');
    //     var sum = data.reduce(function (sum, current){
    //         if(current.delFlag != 1 && current.amount){
    //             return new Big(current.amount).plus(sum);
    //         }
    //         return new Big(sum);
    //     },0)
    //     $("#sum").val(sum);
    // }
    function setSumPrice(){
        var data = $(selector).bootstrapTable('getData');
        var sum = data.reduce(function (sum, current){
            if(current.delFlag != 1 && current.amount && current.num){
                var total = new Big(current.amount).times(current.num).toNumber();
                return new Big(sum).plus(total);
            }
            return new Big(sum);
        },0)
        $("#sum").val(sum);
    }

    /**
     * 监听类型选择回调并更新行
     * @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)
        }
    }
    // function onSelectShelves(nodes, rowIndex){
    //     if(Array.isArray(nodes) && nodes.length === 1){
    //         var node = nodes[0];
    //         var obj = {
    //             shelves: {
    //                 id: node.id,
    //                 name: node.name
    //             },
    //             warehouse: node.warehouse
    //         };
    //         updateRow(rowIndex, obj)
    //     }
    // }

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

    /**
     * 批量添加货架
     */
    function addShelve(){
        // jp.openShelvesSelectDialog(function (items){
        //     var Shelve = items[0]; // 货架对象
        //
        //     getTableData().forEach(function (item,index){
        //         if(item[0]){
        //             updateRow(index,{
        //                 shelves: {
        //                     id: Shelve.id,
        //                     name: Shelve.name
        //                 },
        //                 warehouse: Shelve.warehouse
        //             })
        //         }
        //     })
        // })
        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);
                //     }
                // });
                allSelections.forEach(function (item, index){
                    // var index = getTableData().findIndex(function (current){
                    //     return current.qrCode.id === item.qrCode.id;
                    // }); // 需更新的行的下标
                    updateRow(index, Object.assign({}, obj));
                })
            },200)

        }, true);
    }

    function addDetail(){
        var row =  {
            id: '',
            delFlag: 0,
            name: '',
            type:{
                id: '',
                name: '',
            },
            marking: '',
            shelves: {
                id: '',
                name: ''
            },
            warehouse: {
                id: '',
            },
            amount: null
        }
        $(selector).bootstrapTable('append',[row])
    }

    function onSelectType(nodes, rowIndex){
        if(Array.isArray(nodes) && nodes.length === 1){
            var node = nodes[0];
            var obj = {
                type: {
                    id: node.id,
                    name: node.text,
                    code: node.original.code,
                    unit: node.original.unit
                },
                amount: node.original.amount,
            };
            if ($("#profitWarehousingInfoList" + rowIndex + "_num").val()) {
                obj.infoSum = new Big($("#profitWarehousingInfoList" + rowIndex + "_num").val()).times(obj.amount).toNumber();
            }
            updateRow(rowIndex, obj)
        }
    }

    function delType (idName, id) {
        var name = $("#" + idName + 'Id').attr('name');
        var str1 = name.split('.')[0];
        var startNum = str1.indexOf('[') + 1;
        var str2 = str1.substring(startNum);
        var endNum = str2.length - 1;
        var num = str2.substring(0, endNum);
        var key = "#profitWarehousingInfoList" + num;
        $(key + "_typeCode").val('');
        $(key + "_amount").val('');
        $(key + "_unit").val('');
        $(key + "_infoSum").val('');
        var obj = {
            type: {
                id: '',
                name: '',
                code: '',
                unit: ''
            },
            amount: '',
            infoSum: ''
        };
        updateRow(num, obj);
        setSumPrice();
    }
</script>

<script id="hideTpl" type="text/html">
    <input id="profitWarehousingInfoList{{idx}}_id" name="profitWarehousingInfoList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
    <input id="profitWarehousingInfoList{{idx}}_delFlag" name="profitWarehousingInfoList[{{idx}}].delFlag" type="hidden" value="{{row.delFlag}}"/>
    {{#row.qrCode}}
    <input id="profitWarehousingInfoList{{idx}}_qrCodeId" name="profitWarehousingInfoList[{{idx}}].qrCode.id" type="hidden" value="{{row.qrCode.id}}" readonly class="form-control" />
    {{/row.qrCode}}
    <input id="profitWarehousingInfoList{{idx}}_warehouseId" name="profitWarehousingInfoList[{{idx}}].warehouse.id" type="hidden" value="{{row.warehouse.id}}" readonly class="form-control" />
    <input id="profitWarehousingInfoList{{idx}}_updateFlag" name="profitWarehousingInfoList[{{idx}}].updateFlag" type="hidden" value="{{row.updateFlag}}" readonly class="form-control" />
</script>

<script id="nameTpl" type="text/html">
    {{#row.readonly}}
    <input id="profitWarehousingInfoList{{idx}}_name" name="profitWarehousingInfoList[{{idx}}].name" type="text" value="{{row.name}}" readonly  class="form-control "/>
    {{/row.readonly}}
    {{^row.readonly}}
    <input id="profitWarehousingInfoList{{idx}}_name" name="profitWarehousingInfoList[{{idx}}].name" type="text" value="{{row.name}}" onchange="onInputChange('{{idx}}', this, 'name')"   class="form-control "/>
    {{/row.readonly}}
</script>

<script id="typeTpl" type="text/html">//<!--
    {{#row.readonly}}
    <sys:treeselect id="profitWarehousingInfoList{{idx}}_type" name="profitWarehousingInfoList[{{idx}}].type.id" value="{{row.type.id}}" labelName="profitWarehousingInfoList{{idx}}.type.name" labelValue="{{row.type.name}}"
							title="品名代码" url="/warehouse/materialtype/materialType/treeData" notAllowSelectParent="true" cssClass="form-control required"  allowClear="true" allowSearch="true" disabled="disabled" />
    {{/row.readonly}}
    {{^row.readonly}}
    <sys:treeselect id="profitWarehousingInfoList{{idx}}_type" name="profitWarehousingInfoList[{{idx}}].type.id" value="{{row.type.id}}" labelName="profitWarehousingInfoList{{idx}}.type.name" labelValue="{{row.type.name}}"
                    title="品名代码" url="/warehouse/materialtype/materialType/treeData" notAllowSelectParent="true" cssClass="form-control required"  allowClear="true" allowSearch="true" callback="onSelectType" delCallback="delType" />
    {{/row.readonly}}//-->
</script>
<script id="typeCodeTpl" type="text/html">
    <input id="profitWarehousingInfoList{{idx}}_typeCode" name="profitWarehousingInfoList[{{idx}}].type.code" type="text" value="{{row.type.code}}" readonly class="form-control required"/>
</script>
<script id="modelTpl" type="text/html">
    {{#row.readonly}}
    <input id="profitWarehousingInfoList{{idx}}_marking" name="profitWarehousingInfoList[{{idx}}].marking" type="text" value="{{row.marking}}" readonly    class="form-control "/>
    {{/row.readonly}}
    {{^row.readonly}}
    <input id="profitWarehousingInfoList{{idx}}_marking" name="profitWarehousingInfoList[{{idx}}].marking" type="text" value="{{row.marking}}" onchange="onInputChange('{{idx}}', this, 'marking')"    class="form-control "/>
    {{/row.readonly}}
</script>
<script id="amountTpl" type="text/html">
    <input id="profitWarehousingInfoList{{idx}}_amount" name="profitWarehousingInfoList[{{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="profitWarehousingInfoList{{idx}}_unit" name="profitWarehousingInfoList[{{idx}}].type.unit" type="text" value="{{row.type.unit}}" readonly onchange="onInputChange('{{idx}}', this, 'type.unit')"  class="form-control required"/>
</script>
<script id="numTpl" type="text/html">
    {{#row.readonly}}
        <input id="profitWarehousingInfoList{{idx}}_num" readonly name="profitWarehousingInfoList[{{idx}}].num" type="text"
               value="{{row.num}}" onchange="onInputChange('{{idx}}', this, 'num')"  class="form-control required"/>
    {{/row.readonly}}
    {{^row.readonly}}
        <input id="profitWarehousingInfoList{{idx}}_num" name="profitWarehousingInfoList[{{idx}}].num" type="text"
               value="{{row.num}}" onchange="onInputChange('{{idx}}', this, 'num')"  class="form-control required"/>
    {{/row.readonly}}
</script>
<script id="warehouseTpl" type="text/html">
    <input id="profitWarehousingInfoList{{idx}}_warehouseName"  type="text" value="{{row.warehouseNames}}" readonly  class="form-control "/>
    <input id="profitWarehousingInfoList{{idx}}_warehouseIds" name="profitWarehousingInfoList[{{idx}}].warehouseIds"  type="hidden" value="{{row.warehouseIds}}" readonly  class="form-control "/>
<%--    <input type="hidden" id="profitWarehousingInfoList{{idx}}_shelvesIds" name="profitWarehousingInfoList[{{idx}}].shelvesIds" value="{{row.shelvesIds}}">--%>
</script>
<script id="shelvesTpl" type="text/html">//<!--
  {{#row.readonly}}
  <sys:shelvesselect id="profitWarehousingInfoList{{idx}}_shelves" name="profitWarehousingInfoList[{{idx}}].shelvesIds" value="{{row.shelvesIds}}" labelName="profitWarehousingInfoList[{{idx}}].shelvesNames" labelValue="{{row.shelvesNames}}"
                   cssClass="form-control required" iframeUrl="/warehouse/profitwarehousing/profitWarehousing/form" disabled="disabled" />
  {{/row.readonly}}
  {{^row.readonly}}
  <sys:shelvesselect id="profitWarehousingInfoList{{idx}}_shelves" name="profitWarehousingInfoList[{{idx}}].shelvesIds" value="{{row.shelvesIds}}" labelName="profitWarehousingInfoList[{{idx}}].shelvesNames" labelValue="{{row.shelvesNames}}"
                   cssClass="form-control required" iframeUrl="/warehouse/profitwarehousing/profitWarehousing/form" callback="onSelectShelves" isMultiSelected="true" />
  {{/row.readonly}}//-->
</script>
<script id="remarksTpl" type="text/html">
    {{#row.readonly}}
        <textarea id="profitWarehousingInfoList{{idx}}_remarks" name="profitWarehousingInfoList[{{idx}}].remarks" rows="2"  readonly class="form-control ">{{row.remarks}}</textarea>
    {{/row.readonly}}
    {{^row.readonly}}
        <textarea id="profitWarehousingInfoList{{idx}}_remarks" name="profitWarehousingInfoList[{{idx}}].remarks" rows="2"  onchange="onInputChange('{{idx}}', this, 'remarks')"  class="form-control ">{{row.remarks}}</textarea>
    {{/row.readonly}}
</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>
