<%@ page contentType="text/html;charset=UTF-8" %>
    <script>
    $(document).ready(function() {
        $('#ledgerTable').bootstrapTable({

            //请求方法
            method: 'post',
            //类型json
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            //显示检索按钮
            showSearch: false,
            //显示刷新按钮
            showRefresh: false,
            //显示切换手机试图按钮
            showToggle: false,
            //显示 内容列下拉框
            showColumns: false,
            //显示到处按钮
            showExport: false,
            //显示切换分页按钮
            showPaginationSwitch: false,
            //显示详情按钮
            detailView: true,
            //显示详细内容函数
            detailFormatter: "detailFormatter",
            //最低显示2行
            minimumCountColumns: 2,
            //是否显示行间隔色
            striped: true,
            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            cache: false,
            //是否显示分页（*）
            pagination: true,
            //排序方式
            sortOrder: "asc",
            //初始化加载第一页，默认第一页
            pageNumber:1,
            //每页的记录行数（*）
            pageSize: 10,
            //可供选择的每页的行数（*）
            pageList: [10, 25, 50, 100],
            //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据
            url: "${ctx}/warehouse/ledger/ledger/data",
            //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
            //queryParamsType:'',
            ////查询参数,每次调用是会带上这个参数，可自定义
            queryParams : function(params) {
                var searchParam = $("#searchForm").serializeJSON();
                searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
                searchParam.pageSize = params.limit === undefined? -1 : params.limit;
                searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                return searchParam;
            },
            //分页方式：client客户端分页，server服务端分页（*）
            sidePagination: "server",
            contextMenuTrigger:"right",//pc端 按右键弹出菜单
            contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
            contextMenu: '#context-menu',
            onContextMenuItem: function(row, $el){
                if($el.data("item") == "edit"){
                    edit(row.id);
                }else if($el.data("item") == "view"){
                    view(row.id);
                } else if($el.data("item") == "delete"){
                    jp.confirm('确认要删除该台账信息记录吗？', function(){
                        jp.loading();
                        jp.get("${ctx}/warehouse/ledger/ledger/delete?id="+row.id, function(data){
                            if(data.success){
                                $('#ledgerTable').bootstrapTable('refresh');
                                jp.success(data.msg);
                            }else{
                                jp.error(data.msg);
                            }
                        })

                    });

                }
            },

            onClickRow: function(row, $el){
            },
            onShowSearch: function () {
                $("#search-collapse").slideToggle();
            },
            columns: [
                {
                checkbox: true

                }
                ,{
                    field: 'type.name',
                    title: '品名',
                    sortable: true,
                    sortName: 'name'
                    ,formatter:function(value, row , index){
                        value = jp.unescapeHTML(value);
                        return "<a href='javascript:view(\""+row.id+"\")'>"+value+"</a>";
                    }

                }
                ,{
                    field: 'type.code',
                    title: '代码',
                    sortable: true,
                    sortName: 'type.name'

                },
                // {
                //     field: 'model',
                //     title: '型号',
                //     sortable: true,
                //     sortName: 'model'
                //
                // }
                {
                    field: 'sum',
                    title: '总价',
                    sortable: true,
                    sortName: 'sum'

                }
                ,{
                    field: 'num',
                    title: '数量',
                    sortable: true,
                    sortName: 'num'

                }
                ,{
                    field: 'createDate',
                    title: '创建时间',
                    sortable: true,
                    sortName: 'createDate'

                }
            ]

        });


        if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端


            $('#ledgerTable').bootstrapTable("toggleView");
        }

        $('#ledgerTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#ledgerTable').bootstrapTable('getSelections').length);
            $('#view,#edit').prop('disabled', $('#ledgerTable').bootstrapTable('getSelections').length!=1);
        });

        $("#btnImport").click(function(){
            jp.open({
                type: 2,
                area: [500, 200],
                auto: true,
                title:"导入数据",
                content: "${ctx}/tag/importExcel" ,
                btn: ['下载模板','确定', '关闭'],
                btn1: function(index, layero){
                    jp.downloadFile('${ctx}/warehouse/ledger/ledger/import/template');
                },
                btn2: function(index, layero){
                    var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    iframeWin.contentWindow.importExcel('${ctx}/warehouse/ledger/ledger/import', function (data) {
                        if(data.success){
                            jp.success(data.msg);
                            refresh();
                        }else{
                            jp.error(data.msg);
                        }
                        jp.close(index);
                    });//调用保存事件
                    return false;
                },

                btn3: function(index){
                    jp.close(index);
                }
            });
        });
        // $("#export").click(function(){//导出Excel文件
        //     var searchParam = $("#searchForm").serializeJSON();
        //     searchParam.pageNo = 1;
        //     searchParam.pageSize = -1;
        //     var sortName = $('#ledgerTable').bootstrapTable("getOptions", "none").sortName;
        //     var sortOrder = $('#ledgerTable').bootstrapTable("getOptions", "none").sortOrder;
        //     var values = "";
        //     for(var key in searchParam){
        //         values = values + key + "=" + searchParam[key] + "&";
        //     }
        //     if(sortName != undefined && sortOrder != undefined){
        //         values = values + "orderBy=" + sortName + " "+sortOrder;
        //     }
        //
        //     jp.downloadFile('${ctx}/warehouse/ledger/ledger/export?'+values);
        // })

        $("#search").click("click", function() {// 绑定查询按扭
            $('#ledgerTable').bootstrapTable('refresh');
        });

        $("#reset").click("click", function() {// 绑定查询按扭
            $("#searchForm  input").val("");
            $("#searchForm  select").val("");
            $("#searchForm  .select-item").html("");
            $('#ledgerTable').bootstrapTable('refresh');
        });

        $("#export").click(function () {
            jp.open({
                type: 1,
                title: '导出',
                auto: true,
                area: ['600', '500'],
                content: Mustache.render($("#exportTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{}),
                btn: ['确定', '关闭'],
                success (layeor, i) {
                    var beginTime = layeor.find('#beginTime');
                    var endTime = layeor.find('#endTime');
                    beginTime.datetimepicker({
                        format: "YYYY-MM-DD"
                    });
                    endTime.datetimepicker({
                        format: "YYYY-MM-DD"
                    });
                },
                yes (i, layeor) {
                    var form = layeor.find("#export-searchForm");
                    var isValidate = form.validate().form();
                    if (!isValidate) {
                        return false;
                    } else {
                        var params = form.serializeJSON();
                        params.beginTime = params.beginTime + ' 00:00:00';
                        params.endTime = params.endTime + ' 23:59:59';
                        var str = '';
                        for (var key in params) {
                            str += '&' + key + '=' + params[key]
                        }
                        window.open("${ctx}/warehouse/ledger/ledger/ledgerStreamWater?" + str.substr(1));
                        jp.close(i);
                    }
                },
                cancel () {

                }
            })
        })

    });

function getIdSelections() {
    return $.map($("#ledgerTable").bootstrapTable('getSelections'), function (row) {
        return row.id
    });
}

function deleteAll(){

    jp.confirm('确认要删除该台账信息记录吗？', function(){
        jp.loading();
        jp.get("${ctx}/warehouse/ledger/ledger/deleteAll?ids=" + getIdSelections(), function(data){
            if(data.success){
                $('#ledgerTable').bootstrapTable('refresh');
                jp.success(data.msg);
            }else{
                jp.error(data.msg);
            }
        })

    })
}

//刷新列表
function refresh(){
    $('#ledgerTable').bootstrapTable('refresh');
}
function add(){
    jp.openSaveDialog("新增台账","${ctx}/warehouse/ledger/ledger/form/add", '1400', '800');
}

function edit(id){
    if(id == undefined){
        id = getIdSelections();
    }
    jp.openSaveDialog("编辑台账","${ctx}/warehouse/ledger/ledger/form/edit?id=" + id, '1400', '800');
}

function view(id){//没有权限时，不显示确定按钮
    if(id == undefined){
        id = getIdSelections();
    }
    jp.openViewDialog("查看台账","${ctx}/warehouse/ledger/ledger/form/view?id=" + id,'1400', '800');
}





function detailFormatter(index, row) {
    var htmltpl =  $("#ledgerChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
    var html = Mustache.render(htmltpl, {
        idx:row.id
    });
    $.get("${ctx}/warehouse/ledger/ledger/detail?id="+row.id, function(ledger){
        var ledgerChild1RowIdx = 0, ledgerChild1Tpl = $("#ledgerChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
        var data1 =  ledger.ledgerInfoList;
        for (var i=0; i<data1.length; i++){
            var item = data1[i];
            data1[i].dict = {};
            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(',');
            addRow('#ledgerChild-'+row.id+'-1-List', ledgerChild1RowIdx, ledgerChild1Tpl, data1[i]);
            ledgerChild1RowIdx = ledgerChild1RowIdx + 1;
        }


    })

    return html;
}

function addRow(list, idx, tpl, row){
    $(list).append(Mustache.render(tpl, {
        idx: idx, delBtn: true, row: row
    }));
}

function getTable () {
    return $("#scan_detail_table");
}
// 用于获取扫码信息的input
function getScanIpt () {
    return document.getElementById("scanIpt");
}
// 判断是否是中文输入法
// var inputMethodCnType = false;
// // input持续获取焦点
// var scanIptFocusTimer = null;

function viewScanData () {
    layer.open({
        type: 1,
        title: '扫码',
        auto: true,
        area: ['1200','600'],
        content: $("#scanTpl").html(),
        success: function () {
            // var ipt = getScanIpt();
            // ipt.addEventListener('change', scanDataChange);
            // // ipt.addEventListener('blur', allFocus);
            // ipt.addEventListener('compositionstart', iptCompositionstart);
            // ipt.addEventListener('compositionend', iptCompositionend);
            // scanIptGetFocusStart();
            // $("#scanIpt").focus();
            scanStart();
            renderScanTable();
            // document.addEventListener('visibilitychange', pageVisible);
        },
        cancel: function () {
            // var ipt = getScanIpt();
            // ipt.removeEventListener('change', scanDataChange);
            // // ipt.removeEventListener('blur', allFocus);
            // ipt.removeEventListener('compositionstart', iptCompositionstart);
            // scanIptGetFocusStop();
            // document.removeEventListener('visibilitychange', pageVisible);
            scanStop();
        },
        btn:['关闭']
    })
}

function scanIptChangeCallback (val) {
    var json = JSON.parse(val);
    var params = "qrId=" + json.code;
    getScanData(
        { qrId: json.code },
        function (list) {
            var table = getTable();
            var tableData = table.bootstrapTable('getData');
            list = list.filter(function (item) {
                var i = tableData.find(function (e) {
                    return e.id === item.id;
                })
                return !i;
            });
            if (!list.length) {
                jp.alert('请勿重复扫码');
                return;
            }
            table.bootstrapTable('append', list);
        }
    );
}

// function scanDataChange () {
//     var elem = getScanIpt();
//     var val = $(elem).val();
//     if (!val) {
//         return;
//     }
//     try {
//         var json = JSON.parse(val);
//         var params = "qrId=" + json.code;
//         getScanData(
//             { qrId: json.code },
//             function (list) {
//                 var table = getTable();
//                 var tableData = table.bootstrapTable('getData');
//                 list = list.filter(function (item) {
//                     var i = tableData.find(function (e) {
//                         return e.id === item.id;
//                     })
//                     return !i;
//                 });
//                 if (!list.length) {
//                     jp.alert('请勿重复扫码');
//                     return;
//                 }
//                 table.bootstrapTable('append', list);
//             }
//         );
//     } catch (e) {}
//     setTimeout(function () {
//         $(elem).val('');
//         $(elem).blur();
//     }, 100)
// }

// function iptCompositionstart () {
//     inputMethodCnType = true;
// }
//
// function iptCompositionend () {
//     var ipt = getScanIpt();
//     if (inputMethodCnType) {
//         jp.alert('请将输入法设置为英文');
//         inputMethodCnType = false;
//         ipt.value = '';
//     }
// }

function iptFocus (ipt) {
    var timer = setInterval(function () {
        if (ipt !== document.activeElement) {
            ipt.focus();
        }
    }, 400);
    return timer;
}

// function debounce (callback, timeout = 500) {
//     let timer = null;
//     return function (...arg) {
//         const content = this;
//         if (timer) {
//             clearTimeout(timer);
//         } else {
//             callback.apply(content, arg);
//         }
//         timer = setTimeout(function () {
//             clearTimeout(timer);
//             timer = null;
//         }, timeout)
//     }
// }

function renderScanTable () {
    getTable().bootstrapTable('destroy').bootstrapTable({
        data: [],
        columns: [
            {
                field: 'type.name',
                title: '品名',
                sortable: true,
                sortName: 'type.name'
            },
            {
                field: 'type.code',
                title: '代码',
                sortable: true,
                sortName: 'type.code'
            },
            {
                field: 'code',
                title: '物资编码'
            },
            {
                field: 'batchNum',
                title: '批次号',
            },
            {
                field: 'amount',
                title: '单价'
            },
            {
                field: "type.unit",
                title: '单位'
            },
            // {
            //     field: 'model',
            //     title: '型号',
            //     sortable: true,
            //     sortName: 'model'
            // },
            {
                field: 'num',
                title: '数量'
            },
            {
                field: 'sum',
                title: '总价',
                sortName: 'sum',
                formatter (v, row) {
                    return new Big(row.num).times(row.amount).toNumber()
                }
            },
        ]
    })

}

function searchScanData () {
    var code = $("#scan-code").val();
    getScanData(
        { code: code },
        function (list) {
            getTable().bootstrapTable('load', list);
        }
    )
}
function refreshScanData () {
    $("#scan-code").val('');
    searchScanData();
}


function getScanData (params, callback) {
    var paramsStr = "qrId=" + (params.qrId || '') + "&code=" + (params.code || '');
    jp.get("${ctx}/warehouse/ledger/ledger/findByQrOrCode?" + paramsStr, function (result) {
        if (result && result.rows) {
            callback && callback(result.rows.filter(Boolean));
            // var list = result.rows.filter(Boolean).filter(function (item) {
            //     var i = tableData.find(function (e) {
            //         return e.id === item.id;
            //     })
            //     return !i;
            // });
            // if (!list.length) {
            //     jp.alert('请勿重复扫码');
            //     return;
            // }
            // table.bootstrapTable('append', list);
        } else {
            callback && callback([]);
        }
    })
}

// function pageVisible () {
//     var state = document.visibilityState;
//     if (state === 'visible') {
//         scanIptGetFocusStart();
//     } else if (state === 'hidden') {
//         scanIptGetFocusStop();
//     }
// }

// function scanIptGetFocusStart () {
//     var ipt = getScanIpt();
//     if (ipt) {
//         scanIptFocusTimer = iptFocus(ipt);
//     }
// }
// function scanIptGetFocusStop () {
//     if (scanIptFocusTimer) {
//         clearInterval(scanIptFocusTimer);
//         scanIptFocusTimer = null;
//     }
// }

</script>
<script type="text/template" id="ledgerChildrenTpl">//<!--
	<div class="tabs-container">
		<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-{{idx}}-1" aria-expanded="true">台账明细</a></li>
		</ul>
		<div class="tab-content">
				 <div id="tab-{{idx}}-1" class="tab-pane fade in active">
						<table class="ani table">
						<thead>
							<tr>
								<th>品名</th>
								<th>代码</th>
								<th>物资编码</th>
								<th>数量</th>
								<th>单位</th>
								<th>型号</th>
								<th>单价</th>
								<th>总价</th>
								<th>批次号</th>
								<th>货架</th>
								<th>仓库</th>
								<th>备注</th>
							</tr>
						</thead>
						<tbody id="ledgerChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
</script>
<script type="text/template" id="ledgerChild1Tpl">//<!--
				<tr>
				    <td>
						{{row.type.name}}
					</td>
					<td>
						{{row.type.code}}
					</td>
					<td>{{row.code}}</td>
					<td>
						{{row.num}}
					</td>
					<td>
						{{row.type.unit}}
					</td>
					<td>
						{{row.model}}
					</td>
					<td>
						{{row.amount}}
					</td>
					<td>
						{{row.infoSum}}
					</td>
					<td>
						{{row.batchNum}}
					</td>
					<td>
						{{row.shelvesNames}}
					</td>
	
					<td>
						{{row.warehouseNames}}
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
</script>

