<%--
  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)};
        if(data.length){
            data = data.map(function(item){
                item.delFlag = 0;
                item.readonly = item.qrCode && item.qrCode.state === '2'
                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: 'marking',
                    title: '型号',
                    formatter: function (value,row,index){
                        return Mustache.render($("#modelTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'shelves.name',
                    title: '货架',
                    formatter: function (value,row,index){
                        return Mustache.render($("#shelvesTpl").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: '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){
                        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: row
        })
    }

    /**
     * 监听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 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);
    }

    /**
     * 监听类型选择回调并更新行
     * @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) && 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
                    })
                }
            })
        })
    }

    function addDetail(){
        var row =  {
            id: '',
            delFlag: 0,
            name: '',
            type:{
                id: '',
                name: '',
            },
            marking: '',
            shelves: {
                id: '',
                name: ''
            },
            warehouse: {
                id: '',
            },
            amount: null
        }
        $(selector).bootstrapTable('append',[row])
    }
</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}}"/>
    <input id="profitWarehousingInfoList{{idx}}_warehouseId" name="profitWarehousingInfoList[{{idx}}].warehouse.id" type="hidden" value="{{row.warehouse.id}}" 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" />
    {{/row.readonly}}//-->
</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">
    {{#row.readonly}}
    <input id="profitWarehousingInfoList{{idx}}_amount" name="profitWarehousingInfoList[{{idx}}].amount" type="text" value="{{row.amount}}" readonly   class="form-control "/>
    {{/row.readonly}}
    {{^row.readonly}}
    <input id="profitWarehousingInfoList{{idx}}_amount" name="profitWarehousingInfoList[{{idx}}].amount" type="text" value="{{row.amount}}" onchange="onInputChange('{{idx}}', this, 'amount')"    class="form-control "/>
    {{/row.readonly}}
</script>
<script id="shelvesTpl" type="text/html">//<!--
  {{#row.readonly}}
  <sys:shelvesselect id="profitWarehousingInfoList{{idx}}_shelves" name="profitWarehousingInfoList[{{idx}}].shelves.id" value="{{row.shelves.id}}" labelName="profitWarehousingInfoList[{{idx}}].shelves.name" labelValue="{{row.shelves.name}}"
                   cssClass="form-control required" iframeUrl="/warehouse/profitwarehousing/profitWarehousing/form" disabled="disabled"></sys:shelvesselect>
  {{/row.readonly}}
  {{^row.readonly}}
  <sys:shelvesselect id="profitWarehousingInfoList{{idx}}_shelves" name="profitWarehousingInfoList[{{idx}}].shelves.id" value="{{row.shelves.id}}" labelName="profitWarehousingInfoList[{{idx}}].shelves.name" labelValue="{{row.shelves.name}}"
                   cssClass="form-control required" iframeUrl="/warehouse/profitwarehousing/profitWarehousing/form" callback="onSelectShelves"></sys:shelvesselect>
  {{/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>