<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
	$('#materialPlanTable').bootstrapTable({
		  //请求方法
               method: 'post',
               //类型json
               dataType: "json",
               contentType: "application/x-www-form-urlencoded",
               //显示检索按钮
	           showSearch: true,
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 5,
               //可供选择的每页的行数（*）    
               pageList: [5,10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/sg/managementcenter/materialplan/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.uniqueCode);
                   }else if($el.data("item") == "view"){
                       view(row.uniqueCode);
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该请假表单记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/sg/managementcenter/materialplan/delete?id="+row.uniqueCode, function(data){
                   	  		if(data.success){
                   	  			$('#materialPlanTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   }
               },
              
               onClickRow: function(row, $el){
               },
                onLoadSuccess:function(data){
                    var split = data.rows;
                    for (var i = 0; i < split.length; i++) {
                        $('#'+split[i].uniqueCode).datetimepicker({
                            format: "YYYY-MM-DD"
                        }).on('dp.change',function(i){
                            return function(ev) {
                                var newDateTime = ev.date ? ev.date.format('YYYY-MM-DD') : "";
                                var oldDateTime = ev.oldDate ? ev.oldDate.format('YYYY-MM-DD') : "";
                                if (newDateTime != oldDateTime) {
                                    if (""!=oldDateTime){
                                        jp.confirm('确认要更新时间吗？', function () {
                                            jp.get("${ctx}/sg/managementcenter/materialplan/addtime?uniqueCode=" + split[i].uniqueCode + "&deliverySchedule=" + newDateTime, function (data) {
                                                if (data.success) {
                                                    // jp.success(data.msg);
                                                } else {
                                                    jp.error(data.msg);
                                                }
                                            })
                                        })
                                    }else {
                                        jp.get("${ctx}/sg/managementcenter/materialplan/addtime?uniqueCode=" + split[i].uniqueCode + "&deliverySchedule=" + newDateTime, function (data) {
                                            if (data.success) {
                                                // jp.success(data.msg);
                                            } else {
                                                jp.error(data.msg);
                                            }
                                        })
                                    }

                                }
                            }
                        }(i));
                    }

                    jQuery(function(){
                        //使用id选择器;例如:tab对象->tr->td对象.
                        $("#materialPlanTable tr td").each(function(i){
                            //获取td当前对象的文本,如果长度大于25;
                            if($(this).text().length>10){
                                //给td设置title属性,并且设置td的完整值.给title属性.
                                $(this).attr("title",$(this).text());
                                //获取td的值,进行截取。赋值给text变量保存.
                                var text=$(this).text().substring(0,10)+"...";
                                //重新为td赋值;
                                $(this).text(text);
                            }
                        });
                    });
                },
               	onShowSearch: function () {
			$("#search-collapse").slideToggle();
		},
               columns: [{
		        checkbox: true
		       
		    }
			,{
		        field: 'uniqueCode',
		        title: '物资唯一码（批次编码）',
                       width:180,
		        sortName: 'uniqueCode'
		        ,formatter:function(value, row , index){

			   if(value == null || value ==""){
				   value = "-";
			   }
			   <c:choose>
				   <c:when test="${fns:hasPermission('sg:managementcenter:materialplan:edit')}">
				      return "<a href='javascript:edit(\""+row.uniqueCode+"\")'>"+value+"</a>";
			      </c:when>
				  <c:when test="${fns:hasPermission('sg:managementcenter:materialplan:view')}">
				      return "<a href='javascript:view(\""+row.uniqueCode+"\")'>"+value+"</a>";
			      </c:when>
				  <c:otherwise>
				      return value;
			      </c:otherwise>
			   </c:choose>

		        }
		       
		    }
			,{
		        field: 'requireCoding',
		        title: '需求物资编码',
				width:120,
		        sortName: 'requireCoding'
		       
		    }
			,{
		        field: 'description',
		        title: '物料描述',
                width:180,
		        sortName: 'description'
		       
		    }
			,{
		        field: 'expansionCode',
		        title: '物料扩展编码',
					   width:110,
		        sortName: 'expansionCode'
		    }
			,{
		        field: 'expansionDescription',
		        title: '物料扩展描述',
                width:200,
		        sortName: 'expansionDescription'

		    }
                   ,{
                       field: 'deliverySchedule',
                       title: '供货计划到日',
                       width:160,
                       sortName: 'deliverySchedule',
                       formatter: getTime
                   }
                   ,{
                       field: 'bigDescribe',
                       title: '大类描述',
                       width:120,
                       sortName: 'bigDescribe'

                   }
                   ,{
                       field: 'moderateDescribe',
                       title: '中类描述',
                       width:120,
                       sortName: 'moderateDescribe'

                   }
                   ,{
                       field: 'smallDescribe',
                       title: '小类描述',
                       width:120,
                       sortName: 'smallDescribe'

                   }
                   ,{
                       field: 'requireNumber',
                       title: '需求数量',
                       width:80,
                       sortName: 'requireNumber'
                   }
                   ,{
                       field: 'util',
                       title: '单位',
                       width:50,
                       sortName: 'util'

                   }
                   ,{
                       field: 'planToBatch',
                       title: '计划批次',
                       width:120,
                       sortName: 'planToBatch'

                   }
                   ,{
                       field: 'flagStorage',
                       title: '是否入库',
                       width:120,
                       sortName: 'flagStorage'
                   }
                   ,{
                       field: 'inventoryQuantity',
                       title: '库存数量',
                       width:120,
                       sortName: 'inventoryQuantity'
                   }
                   ,{
                       field: 'numberFrozen',
                       title: '冻结数量',
                       width:120,
                       sortName: 'numberFrozen'
                   }
                   ,{
                       field: 'supplierName',
                       title: '供应商名称',
                       width:200,
                       sortName: 'supplierName'
                   }
		     ]
		
		});
		// function getTime(value, row, index) {
		// 	return [
		// 		"<div class='input-group form_datetime' id="+row.uniqueCode+"  onclick=\"listDate( '" + row.uniqueCode +" ')\"> <input type='text'   name='deliverySchedule' class='form-control required'  value=''/> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'></span> </span></div>" ,
		// 	].join('');
		// }
        function getTime(value, row, index) {
            return [
                "<div class='input-group form_datetime' id="+row.uniqueCode+"> <input type='text'   name='deliverySchedule' class='form-control required'  value="+row.deliverySchedule+"/> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'></span> </span></div>" ,
            ].join('');
        }
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#materialPlanTable').bootstrapTable("toggleView");
		}
	  
	  $('#materialPlanTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#materialPlanTable').bootstrapTable('getSelections').length);
            $('#view,#edit').prop('disabled', $('#materialPlanTable').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){
				        var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
						iframeWin.contentWindow.importExcel('${ctx}/sg/managementcenter/materialplan/import', function (data) {
							if(data.success){
								jp.success(data.msg);
								refresh();
							}else{
								jp.error(data.msg);
							}
                            jp.close(index);
						});//调用保存事件
						return false;
				  	},

				  btn2: function(index){
					//  jp.close(index);
	    	       }
			}); 
		});
		
		
	 $("#export").click(function(){//导出Excel文件
			jp.downloadFile('${ctx}/sg/managementcenter/materialplan/export');
	  });
        $("#export1").click(function(){//导出Excel文件
            jp.downloadFile('${ctx}/sg/managementcenter/materialplan/import/template');
        });
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#materialPlanTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		  $("#searchForm  .select-item").html("");
		  $('#materialPlanTable').bootstrapTable('refresh');
		});

		$('.beginDate').datetimepicker({
			 format: "YYYY-MM-DD"
		});
		$('#endBeginDate').datetimepicker({
			 format: "YYYY-MM-DD HH:mm:ss"
		});
		$('#endDate').datetimepicker({
			 format: "YYYY-MM-DD HH:mm:ss"
		});
		
	});
		
  function getIdSelections() {
        return $.map($("#materialPlanTable").bootstrapTable('getSelections'), function (row) {
            return row.uniqueCode
        });
    }
  
  function deleteAll(){
		jp.confirm('确认要删除该物料计划表单记录吗？', function(){
          jp.loading();
          jp.get("${ctx}/sg/managementcenter/materialplan/deleteAll?ids=" + getIdSelections(), function(data){
              if(data.success){
                  $('#materialPlanTable').bootstrapTable('refresh');
                  jp.success(data.msg);
              }else{
                  jp.error(data.msg);
              }
          })
      })
  }

    //刷新列表
  function refresh(){
  	$('#materialPlanTable').bootstrapTable('refresh');
  }
  
   function add(){
	  jp.openSaveDialog('新增物料计划表单', "${ctx}/sg/managementcenter/materialplan/form",'800px', '500px');
  }


  
   function edit(id){//没有权限时，不显示确定按钮
       if(id == undefined){
	      id = getIdSelections();
	}
	jp.openSaveDialog('编辑物料计划表单', "${ctx}/sg/managementcenter/materialplan/form?id=" + id, '800px', '500px');
  }
  
 function view(id){//没有权限时，不显示确定按钮
      if(id == undefined){
             id = getIdSelections();
      }
        jp.openViewDialog('查看物料计划表单', "${ctx}/sg/managementcenter/materialplan/form?id=" + id, '800px', '500px');
 }

</script>