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

                    });

                }
            },

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

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

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

                }
                ,{
                    field: 'office.name',
                    title: '领用机构',
                    sortable: true,
                    sortName: 'o.name'

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

                },
                {
                    field: 'status',
                    title: '出库状态',
                    sortable: true,
                    sortName: 'status',
                    formatter:function(value, row , index){
                        return jp.getDictLabel(${fns:toJson(fns:getDictList('wh_delivery_status'))}, value, "-");
                    }

                },
                {
                    field: 'remarks',
                    title: '备注信息',
                    sortable: true,
                    sortName: 'remarks'
                },
                {
                    title: '操作',
                    formatter (v, r) {
                        if (r.status === '1') {
                            return "<a class='delivery'>出库</a>"
                        }
                    },
                    events: {
                        'click .delivery': function (e, v, r) {
                            onDelivery(r.id);
                        }
                    }
                }
            ]

        });


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


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

        $('#materialRequisitionTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {

            var list = $('#materialRequisitionTable').bootstrapTable('getSelections');
            var canUseList = list.filter(function (item) {
                return item.status != '2';
            })
            $("#remove").prop('disabled', !canUseList.length);
            $("#edit").prop('disabled', canUseList.length !== 1);
            $("#view").prop('disabled', list.length !== 1);
            $('#delivery').prop('disabled', !(list.length === 1 && list[0].status == '1'));

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

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

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


    });

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

function deleteAll(){
    var list = $("#materialRequisitionTable").bootstrapTable('getSelections');
    var canDelList = list.filter(function (e) {
        return e.status != '2';
    })
    var canNotDelList = list.filter(function (e) {
        return e.status == '2';
    })
    var ids = canDelList.map(function (e) {
        return e.id;
    })
    if (!ids.length) {
        jp.alert('所选数据为已出库数据，不可删除');
        return;
    }
    var text = '确认要删除该物资领用记录吗？';
    if (canNotDelList.length) {
        text = '所选数据有已出库数据，将删除未出库数据，确认要删除该物资领用记录吗？';
    }
    jp.confirm(text, function(){
        jp.loading();
        jp.get("${ctx}/warehouse/materialrequisition/materialRequisition/deleteAll?ids=" + ids, function(data){
            if(data.success){
                $('#materialRequisitionTable').bootstrapTable('refresh');
                jp.success(data.msg);
            }else{
                jp.error(data.msg);
            }
        })

    })
}

//刷新列表
function refresh(){
    $('#materialRequisitionTable').bootstrapTable('refresh');
}
function add(){
    jp.openSaveDialog("新增物资领用","${ctx}/warehouse/materialrequisition/materialRequisition/form/add",'1200','800');
}

function edit(id){
    if(id == undefined){
        id = getIdSelections();
    }
    jp.openSaveDialog("编辑物资领用","${ctx}/warehouse/materialrequisition/materialRequisition/form/edit?id=" + id, '1200','800');
}

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





function detailFormatter(index, row) {
    var htmltpl =  $("#materialRequisitionChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
    var html = Mustache.render(htmltpl, {
        idx:row.id
    });
    $.get("${ctx}/warehouse/materialrequisition/materialRequisition/detail?id="+row.id, function(materialRequisition){
        var materialRequisitionChild1RowIdx = 0, materialRequisitionChild1Tpl = $("#materialRequisitionChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
        var data1 =  materialRequisition.materialRequisitionInfoList;
        for (var i=0; i<data1.length; i++){
            data1[i].dict = {};
            addRow('#materialRequisitionChild-'+row.id+'-1-List', materialRequisitionChild1RowIdx, materialRequisitionChild1Tpl, data1[i]);
            materialRequisitionChild1RowIdx = materialRequisitionChild1RowIdx + 1;
        }


    })

    return html;
}

function addRow(list, idx, tpl, row){
    row.ledgerInfo.shelvesNames = row.ledgerInfo.shelvesList ? row.ledgerInfo.shelvesList.map(function (e) { return e.name }).join(',') + ',' : '';
    row.ledgerInfo.warehouseNames = row.ledgerInfo.warehouseList ? row.ledgerInfo.warehouseList.map(function (e) { return e.name }).join(',') + ',' : '';
    $(list).append(Mustache.render(tpl, {
        idx: idx, delBtn: true, row: row
    }));
}

/**
 * 出库
 */
function onDelivery (id) {
    if (!id) {
        id = getIdSelections();
    }
    jp.confirm('确认是否出库？', function (){
        jp.get('${ctx}/warehouse/materialrequisition/materialRequisition/delivery?id='+ id, function (res){
            if (res.success) {
                jp.success(res.msg);
                refresh();
            } else {
                jp.error(res.msg);
            }
        })
    })
}
</script>
<script type="text/template" id="materialRequisitionChildrenTpl">//<!--
	<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>
							</tr>
						</thead>
						<tbody id="materialRequisitionChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
</script>
<script type="text/template" id="materialRequisitionChild1Tpl">//<!--
				<tr>
					<td>
						{{row.ledgerInfo.code}}
					</td>
					<td>
						{{row.ledgerInfo.type.name}}
					</td>
					<td>
						{{row.ledgerInfo.type.code}}
					</td>
					<td>
						{{row.ledgerInfo.type.unit}}
					</td>
					<td>
						{{row.ledgerInfo.model}}
					</td>
					<td>
						{{row.ledgerInfo.amount}}
					</td>
					<td>
						{{row.ledgerInfo.batchNum}}
					</td>
					<td>
						{{row.ledgerInfo.shelvesNames}}
					</td>
					<td>
						{{row.ledgerInfo.warehouseNames}}
					</td>
					<td>
						<img src="{{row.receiver}}" width="80"/>
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
</script>
