<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
	$('#storageTable').bootstrapTable({
		 
		  //请求方法
               method: 'post',
               //类型json
               dataType: "json",
               contentType: "application/x-www-form-urlencoded",
               //显示检索按钮
	       showSearch: true,
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //显示详情按钮
    	       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/storage/storage/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/storage/storage/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#storageTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
               	onShowSearch: function () {
			$("#search-collapse").slideToggle();
		},
               columns: [{
		        checkbox: true
		       
		    }
			,{
		        field: 'code',
		        title: '入库单',
		        sortable: true,
		        sortName: 'code'
		        ,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: 'time',
		        title: '时间',
		        sortable: true,
		        sortName: 'time'
		       
		    }
			,{
		        field: 'batchNum',
		        title: '批次号',
		        sortable: true,
		        sortName: 'batchNum'
		       
		    }
			,{
		        field: 'remarks',
		        title: '备注信息',
		        sortable: true,
		        sortName: 'remarks'
		       
		    }
		     ]
		
		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#storageTable').bootstrapTable("toggleView");
		}
	  
	  $('#storageTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#storageTable').bootstrapTable('getSelections').length);
            $('#view,#edit').prop('disabled', $('#storageTable').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/storage/storage/import/template');
				  },
			    btn2: function(index, layero){
				        var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
						iframeWin.contentWindow.importExcel('${ctx}/warehouse/storage/storage/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 = $('#storageTable').bootstrapTable("getOptions", "none").sortName;
            var sortOrder = $('#storageTable').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/storage/storage/export?'+values);
	  })
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#storageTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		   $("#searchForm  .select-item").html("");
		  $('#storageTable').bootstrapTable('refresh');
		});
		
				$('#beginTime').datetimepicker({
					 format: "YYYY-MM-DD HH:mm:ss"
				});
				$('#endTime').datetimepicker({
					 format: "YYYY-MM-DD HH:mm:ss"
				});
		
	});
		
  function getIdSelections() {
        return $.map($("#storageTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
  
  function deleteAll(){

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

     //刷新列表
  function refresh(){
  	$('#storageTable').bootstrapTable('refresh');
  }
  function add(){
		jp.openSaveDialog("新增入库单","${ctx}/warehouse/storage/storage/form/add", '1200', '800');
	}

  function edit(id){
	  if(id == undefined){
		  id = getIdSelections();
	  }
	  jp.openSaveDialog("编辑入库单","${ctx}/warehouse/storage/storage/form/edit?id=" + id, '1200', '800');
  }
  
 function view(id){//没有权限时，不显示确定按钮
      if(id == undefined){
             id = getIdSelections();
      }
         jp.openViewDialog("查看入库单","${ctx}/warehouse/storage/storage/form/view?id=" + id, '1200', '800');
 }

  
  
  
		   
  function detailFormatter(index, row) {
	  var htmltpl =  $("#storageChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
	  var html = Mustache.render(htmltpl, {
			idx:row.id
		});
	  $.get("${ctx}/warehouse/storage/storage/countStorage?id="+row.id, function(storage){
    	var storageChild1RowIdx = 0, storageChild1Tpl = $("#storageChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data1 =  storage.countStorageInfoList;
		for (var i=0; i<data1.length; i++){
			data1[i].dict = {};
			data1[i].storageId = row.id;
			data1[i].batchNum = row.batchNum;
			data1[i].jsonStr = JSON.stringify(data1[i]);
			data1[i].isNotStorage = data1[i].state === '1';
			data1[i].isStorage = data1[i].state === '2';
			data1[i].mainRowIndex = index;
			addRow('#storageChild-'+row.id+'-1-List', storageChild1RowIdx, storageChild1Tpl, data1[i]);
			storageChild1RowIdx = storageChild1RowIdx + 1;
		}
				
      	  			
      })
     
        return html;
    }
  
	function addRow(list, idx, tpl, row){
		$(list).append(Mustache.render(tpl, {
			idx: idx, delBtn: true, row: row
		}));
	}

	function onStorage(countStorage, goodsInfoId, rowIndex){
		var main = JSON.parse(countStorage);
	  jp.get("${ctx}/warehouse/storage/storage/findInfoBycountStorage?goodsInfo.id="+goodsInfoId+"&storage.id="+main.storageId, function (res){
		  var data = res.body.storageInfoList;
		  if(Array.isArray(data)){
			  var shelvesIds = data.map(function (item){
				  return item.shelves.id
			  }).join(',');
			  // 构建台账主表
			  var name$ = $("<input type='hidden' name='name' value='"+main.name+"' />");
			  var typeId$ = $("<input type='hidden' name='type.id' value='"+main.type.id+"' />");
			  var typeName$ = $("<input type='hidden' name='type.name' value='"+main.type.name+"' />");
			  var model$ = $("<input type='hidden' name='model' value='"+main.model+"' />");
			  var shelvesIds$ = $("<input type='hidden' name='shelvesIds' value='"+shelvesIds+"' />");
			  var num$ = $("<input type='hidden' name='num' value="+main.num+" />");
			  var sum$ = $("<input type='hidden' name='sum' value="+main.sum+" />");
			  $("#ledgerForm").empty();
			  $("#ledgerForm").append(name$).append(typeId$).append(typeName$).append(model$).append(shelvesIds$).append(num$).append(sum$);
			  data.forEach(function (item,index){
				  // 构建台账附表
				  var id$ = $("<input type='hidden' name='ledgerInfoList["+index+"].id' value='' />");
				  var delFlag$ = $("<input type='hidden' name='ledgerInfoList["+index+"].delFlag' value='0' />");
				  var name$ = $("<input type='hidden' name='ledgerInfoList["+index+"].name' value='"+item.name+"' />");
				  var typeId$ = $("<input type='hidden' name='ledgerInfoList["+index+"].type.id' value='"+item.type.id+"' />");
				  var batchNum$ = $("<input type='hidden' name='ledgerInfoList["+index+"].batchNum' value='"+main.batchNum+"' />");
				  var model$ = $("<input type='hidden' name='ledgerInfoList["+index+"].model' value='"+item.model+"' />");
				  var goodsInfoId$ = $("<input type='hidden' name='ledgerInfoList["+index+"].goodsInfo.id' value='"+item.goodsInfo.id+"' />");
				  var qrId$ = $("<input type='hidden' name='ledgerInfoList["+index+"].qr.id' value='"+item.qrCode.id+"' />");
				  var shelvesId$ = $("<input type='hidden' name='ledgerInfoList["+index+"].shelves.id' value='"+item.shelves.id+"' />");
				  var code$ = $("<input type='hidden' name='ledgerInfoList["+index+"].code' value='"+item.qrCode.code+"' />");
				  var amount$ = $("<input type='hidden' name='ledgerInfoList["+index+"].amount' value='"+item.amount+"' />");
				  $("#ledgerForm").append(id$).append(delFlag$).append(name$).append(typeId$).append(batchNum$).append(model$).append(goodsInfoId$).append(qrId$).append(shelvesId$).append(code$).append(amount$);
			  })
			  jp.loading('入库中...');
			  jp.post("${ctx}/warehouse/ledger/ledger/save", $("#ledgerForm").serialize(), function (res){
				  if(res.success){
					  jp.success('入库成功！');
					  $('#storageTable').bootstrapTable('collapseRow', rowIndex);
					  setTimeout(function (){
						  $('#storageTable').bootstrapTable('expandRow', rowIndex);
					  },0)
				  }else {
					  jp.error('入库失败！');
				  }
			  })
		  }
	  })
	}
			
</script>
<script type="text/template" id="storageChildrenTpl">//<!--
	<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>
							</tr>
						</thead>
						<tbody id="storageChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
	</script>
	<script type="text/template" id="storageChild1Tpl">//<!--
				<tr>
					<td>
						{{row.name}}
					</td>
					<td>
						{{row.type.name}}
					</td>
					<td>
						{{row.model}}
					</td>
					<td>
						{{row.warehouseNames}}
					</td>
					<td>
						{{row.shelvesNames}}
					</td>
					<td>
						{{row.sum}}
					</td>
					<td>
						{{row.num}}
					</td>
					{{#row.isNotStorage}}
					<td>
					   <a href="javascript:void(0);" onclick="onStorage('{{row.jsonStr}}','{{row.goodsInfo.id}}',{{row.mainRowIndex}})">入库</a>
					</td>
					{{/row.isNotStorage}}
					{{#row.isStorage}}
					<td>
					   已入库
					</td>
					{{/row.isStorage}}
				</tr>//-->
	</script>
