<%@ page contentType="text/html;charset=UTF-8" %>
    <script>
var LODOP;
$(document).ready(function() {
    $('#goodsTable').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/goods/goods/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/goods/goods/delete?id="+row.id, function(data){
                        if(data.success){
                            $('#goodsTable').bootstrapTable('refresh');
                            jp.success(data.msg);
                        }else{
                            jp.error(data.msg);
                        }
                    })

                });

            }
        },

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

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

            }
            ,{
                field: 'time',
                title: '时间',
                sortable: true,
                sortName: 'time'

            }
            ,{
                field: 'remarks',
                title: '备注信息',
                sortable: true,
                sortName: 'remarks'

            }
            ,{
                field: 'operator.name',
                title: '操作人',
                sortable: true,
                sortName: 'operator.name'

            }
        ]

    });


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


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

    $('#goodsTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
        'check-all.bs.table uncheck-all.bs.table', function () {
        $('#remove').prop('disabled', ! $('#goodsTable').bootstrapTable('getSelections').length);
        $('#view,#edit').prop('disabled', $('#goodsTable').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/goods/goods/import/template');
            },
            btn2: function(index, layero){
                var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                iframeWin.contentWindow.importExcel('${ctx}/warehouse/goods/goods/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 = $('#goodsTable').bootstrapTable("getOptions", "none").sortName;
        var sortOrder = $('#goodsTable').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/goods/goods/export?'+values);
    })

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

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

    $('#beginTime').datetimepicker({
        format: "YYYY-MM-DD HH:mm:ss"
    });
    $('#endTime').datetimepicker({
        format: "YYYY-MM-DD HH:mm:ss"
    });

});

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

function deleteAll(){
    jp.confirm('确认要删除该货品模块记录吗？', function(){
        jp.loading();
        const ids = getIdSelections();

        getDetails(ids, function (canDel) {
            if (canDel) {
                jp.get("${ctx}/warehouse/goods/goods/deleteAll?ids=" + ids, function(data){
                    if(data.success){
                        $('#goodsTable').bootstrapTable('refresh');
                        jp.success(data.msg);
                    }else{
                        jp.error(data.msg);
                    }
                })
            } else {
                jp.warning('有已入库的明细数据，不可删除');
            }
        });

    })
}

function getDetails (ids, callback) {

    var l = ids.length;
    var canDel = true;
    var i = 0;

    getDetail$(i);

    function getDetail$ (index) {
        if (!canDel || index === l) {
            callback && callback(canDel);
            return
        }
        var id = ids[index];
        $.get("${ctx}/warehouse/goods/goods/detail?id="+id, function (result) {
            var list =  result.goodsInfoList;

            canDel = list.every(function (el) {
                return el.qrCode ? Number(el.qrCode.state) === 0 : true;
            });
            console.log(canDel)
            i++;
            getDetail$(i);
        });
    }

}

//刷新列表
function refresh(){
    $('#goodsTable').bootstrapTable('refresh');
}
function add(){
    jp.openSaveDialog('新增货品', "${ctx}/warehouse/goods/goods/form/add", '1200', '800')
}

function edit(id){
    if(id == undefined){
        id = getIdSelections();
    }
    jp.openSaveDialog("编辑货品","${ctx}/warehouse/goods/goods/form/edit?id=" + id, '1200', '800');
}

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





function detailFormatter(index, row) {
    var htmltpl =  $("#goodsChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
    var html = Mustache.render(htmltpl, {
        idx:row.id
    });
    $.get("${ctx}/warehouse/goods/goods/detail?id="+row.id, function(goods){
        var goodsChild1RowIdx = 0, goodsChild1Tpl = $("#goodsChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
        var data1 =  goods.goodsInfoList;
        for (var i=0; i<data1.length; i++){
            data1[i].dict = {};
            data1[i].dict.state = jp.getDictLabel(${fns:toJson(fns:getDictList('wh_stockroom_state'))}, data1[i].state, "-");
            addRow('#goodsChild-'+row.id+'-1-List', goodsChild1RowIdx, goodsChild1Tpl, data1[i]);
            goodsChild1RowIdx = goodsChild1RowIdx + 1;
        }


    })

    return html;
}

function initLodop(){
    LODOP=getLodop(document.getElementById('LODOP_OB'),document.getElementById('LODOP_EM'));
}

function addRow(list, idx, tpl, row){
    $(list).append(Mustache.render(tpl, {
        idx: idx, delBtn: true, row: row,
        showAction: function () {
            return row.qrCode ? !(row.qrCode.state !== '0') : true;
        }
    }));
}

function printQr_(id) {
    try{
        if(!LODOP){
            initLodop();
        }
        if(LODOP){
            jp.loading('loading...');
            jp.get("${ctx}/warehouse/goods/goods/printQr?goodsInfoId="+id, function (res) {
                var row = res.body.goodsInfo.qrCode;
                LODOP.PRINT_INIT("打印货品");
                LODOP.SET_PRINT_PAGESIZE(1, 1600, 1000, 0)
                createAllPage(row);
                LODOP.PREVIEW();
                jp.close();
            })
        }
    }catch (e){
        jp.get("${ctx}/warehouse/goods/goods/printQr?goodsInfoId="+id, function (res) {
            var list = res.body.goodsInfo.qrCodeList;
            jp.close();
        })
    }
}

function printQr (id) {
    jp.loading('loading...');
    jp.get("${ctx}/warehouse/goods/goods/printQr?goodsInfoId="+id, function (res) {
        if (res.success) {
            var row = res.body.goodsInfo.qrCode;
            var imgUrl = "${ctxPath}/" + row.url;
            // jp.showPic(imgUrl);
            _thermal_Image_print_(imgUrl);
        }
        jp.close();
    })
}

function createAllPage(item){

    // if(!list){
    //   return;
    // }
    //  list.forEach(function(item){
    //    LODOP.NewPage();
    //    var imgUrl = "${ctxPath}/" + item.url;
    //    LODOP.ADD_PRINT_IMAGE('0%',"0%","100%","100%","<img width='150'  border='0' src='"+imgUrl+"' />");
    //  })
    LODOP.NewPage();
    var imgUrl = "${ctxPath}/" + item.url;
    LODOP.ADD_PRINT_IMAGE('0%',"0%","100%","100%","<img width='800' border='0' src='"+imgUrl+"' />");
    LODOP.SET_PRINT_STYLEA(0,"Stretch",1)
}

function cleanQr(id) {
    jp.confirm('确认清除二维码吗？', function (){
        jp.get("${ctx}/warehouse/goods/goods/cleanQr?goodsInfoId="+id, function (res) {
            res.success && jp.success('清除二维码成功！');
        })
    })
}

</script>
<script type="text/template" id="goodsChildrenTpl">//<!--
	<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>
							</tr>
						</thead>
						<tbody id="goodsChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
</script>
<script type="text/template" id="goodsChild1Tpl">//<!--
				<tr>
					<td>
						{{row.type.name}}
					</td>
					<td>
						{{row.type.code}}
					</td>
					<td>
						{{row.model}}
					</td>
					<td>
						{{row.num}}
					</td>
					<td>
						{{row.amount}}
					</td>
					<td>
						{{row.type.unit}}
					</td>
					<td>
						{{row.infoSum}}
					</td>
					<td>
						{{row.remarks}}
					</td>
					<td>
					{{#showAction}}
						<button class="btn btn-primary btn-sm" onclick="printQr('{{row.id}}')">
							打印二维码
						</button>
						<button class="btn btn-danger btn-sm" onclick="cleanQr('{{row.id}}')">
							清除二维码
						</button>
						{{/showAction}}
					</td>
				</tr>//-->
</script>
