<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<link rel="stylesheet" href="${contextPath}/static/assets/css/jquery-ui.css" />
<link rel="stylesheet" href="${contextPath}/static/assets/css/ui.jqgrid.css" />
<link rel="stylesheet" href="${contextPath}/static/assets/css/datepicker.css" />
<style>
	.div-a{ float:left;} 
	.div-b{ float:left;} 
</style>

<div class="row">
	<div class="col-xs-12">
		<table id="grid-table"></table>
		<div id="grid-pager"></div>
		<script type="text/javascript">
			var $path_base = "${contextPath}/static";//in Ace demo this will be used for editurl parameter
		</script>
	</div><!-- /.col -->
</div><!-- /.row -->

<div id="mod-add" class="modal fade" tabindex="-1" data-backdrop="static">
	<div class="modal-dialog" style="max-width: 600px;">
		<div class="modal-content">
			<div class="modal-header no-padding">
      			<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					新增兑换码
				</div>
	      	</div>
	      	<div class="modal-body">
	      		<form id="viewForm" class="form-horizontal">
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">兑换码</label>
			      		<div class="col-sm-8 text-left">
			      			<input type="text" id="mod-add-redeemCode" class="form-control" />
			      		</div>
			      		<div class="col-sm-2 text-left">
			      			<button type="button" class="btn btn-minier btn-primary" style="height:34px;" id="mod-add-redeemCode-button">前台获取</button>
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">使用次数</label>
			      		<div class="col-sm-10 text-left">
			      			<input type="text" id="mod-add-quantity" class="form-control" />
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">套餐名</label>
			      		<div class="col-sm-10 text-left">
			      			<select class="form-control" id="mod-add-productName"></select>
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">有效期</label>
			      		<div class="col-sm-10 text-left">
			      			<input type="text" id="mod-add-expiryDate" class="form-control" />
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">备注</label>
			      		<div class="col-sm-10 text-left">
			      			<textarea id="mod-add-remark" class="form-control" rows="3"/>
			      		</div>
			      	</div>
		      	</form>
	      	</div>
	      	<div class="modal-footer no-margin-top">
                <div class="text-center">
					<button id="mod-add-submit" type="button" class="btn btn-sm btn-primary">
						<i class="ace-icon fa fa-floppy-o bigger-160"></i>
						保存
					</button>
					<button class="btn btn-sm" data-dismiss="modal">
						<i class="ace-icon fa fa-share bigger-160"></i>
						取消
					</button>
				</div>
			</div>
		</div>
	</div>
</div>

<div id="mod-edit" class="modal fade" tabindex="-1" data-backdrop="static">
	<div class="modal-dialog" style="max-width: 600px;">
		<div class="modal-content">
			<div class="modal-header no-padding">
      			<div class="table-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						<span class="white">&times;</span>
					</button>
					修改兑换码
				</div>
	      	</div>
	      	<div class="modal-body">
	      		<form id="viewForm" class="form-horizontal">
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">兑换码</label>
			      		<div class="col-sm-10 text-left">
			      			<input type="text" id="mod-edit-redeemCode" class="form-control" readonly="readonly"/>
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">使用次数</label>
			      		<div class="col-sm-10 text-left">
			      			<input type="text" id="mod-edit-quantity" class="form-control" />
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">套餐名</label>
			      		<div class="col-sm-10 text-left">
			      			<select class="form-control" id="mod-edit-productName"></select>
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">有效期</label>
			      		<div class="col-sm-10 text-left">
			      			<input type="text" id="mod-edit-expiryDate" class="form-control" />
			      		</div>
			      	</div>
			      	<div class="hr-line-dashed"></div>
			      	<div class="form-group">
			      		<label class="col-sm-2 control-label">备注</label>
			      		<div class="col-sm-10 text-left">
			      			<textarea id="mod-edit-remark" class="form-control" rows="3"/>
			      			<input type="hidden" id="mod-edit-id"/>
			      		</div>
			      	</div>
		      	</form>
	      	</div>
	      	<div class="modal-footer no-margin-top">
                <div class="text-center">
					<button id="mod-edit-submit" type="button" class="btn btn-sm btn-primary">
						<i class="ace-icon fa fa-floppy-o bigger-160"></i>
						保存
					</button>
					<button class="btn btn-sm" data-dismiss="modal">
						<i class="ace-icon fa fa-share bigger-160"></i>
						取消
					</button>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- page specific plugin scripts -->
<script type="text/javascript">
	var currentProductName = null;
	var myGrid = null;
	var scripts = [ null, "${contextPath}/static/assets/js/jqGrid/jquery.jqGrid.js", "${contextPath}/static/assets/js/jqGrid/i18n/grid.locale-cn.js","${contextPath}/static/assets/js/date-time/bootstrap-datepicker.js","${contextPath}/static/assets/js/date-time/locales/bootstrap-datepicker.zh-CN.js", null ];
	$('.page-content-area').ace_ajax('loadScripts', scripts, function() {
		var numberAndLetters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
		                        'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
		                        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
		// inline scripts related to this page
     	jQuery(function($) {
     		var grid_selector = "#grid-table";
     		var pager_selector = "#grid-pager";

     		// resize to fit page size
     		$(window).on('resize.jqGrid', function() {
     			$(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
     		})
     		// resize on sidebar collapse/expand
     		var parent_column = $(grid_selector).closest('[class*="col-"]');
     		$(document).on('settings.ace.jqGrid', function(ev, event_name, collapsed) {
     			if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
     				// setTimeout is for webkit only to give time for DOM changes and then redraw!!!
     				setTimeout(function() {
     					$(grid_selector).jqGrid('setGridWidth', parent_column.width());
     				}, 0);
     			}
     		});

     		myGrid = jQuery(grid_selector).jqGrid({
     			subGrid : false,
     			url : "${contextPath}/sys/redeem/getCodes",
     			datatype : "json",
     			height : '99%',
     			colModel : [  {
     				name : 'id',
     				label : '',
     				width : 80,
       				viewable:false,
       				hidden : true,
     			},{
     				name : 'code',
     				label : '兑换码',
     				width : 80,
     			},{
     				name : 'quantity',
     				label : '使用次数',
     				width : 80,
     			},{
     				name : 'productName',
     				label : '套餐名',
     				width : 200,
     			}, {
     				name : 'expiryDate',
     				label : '有效期',
     				width : 100,
     			}, {
     				name : 'createDate',
     				label : '创建时间',
     				width : 100,
     			}, {
     				name : 'remark',
     				label : '备注',
     				width : 100,
     			}],
     			//scroll : 1, // set the scroll property to 1 to enable paging with scrollbar - virtual loading of records
     			sortname : "createDate",
     			sortorder : "desc",
     			viewrecords : true,
     			rowNum : 10,
     			rowList : [ 10, 20, 30 ],
     			pager : pager_selector,
     			altRows : true,
       			multiselect : true,
     			loadComplete : function() {
     				var table = this;
     				setTimeout(function(){
     					updatePagerIcons(table);
     					enableTooltips(table);
     				}, 0);
     			},
     		});

     		$(window).triggerHandler('resize.jqGrid');// trigger window resize to make the grid get the correct size
     		
     		jQuery(grid_selector).jqGrid('navGrid', pager_selector, {
     			edit : false,
       			editicon : 'ace-icon fa fa-pencil blue',
       			add : false,
       			addicon : 'ace-icon fa fa-plus-circle purple',
       			del : false,
       			delicon : 'ace-icon fa fa-trash-o red',
       			search : false,
       			searchicon : 'ace-icon fa fa-search orange',
       			refresh : false,
       			refreshicon : 'ace-icon fa fa-refresh blue',
       			view : false,
     		});

     		// replace icons with FontAwesome icons like above
     		function updatePagerIcons(table) {
     			var replacement = {
     				'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
     				'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
     				'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
     				'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
     			};
     			$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function() {
     				var icon = $(this);
     				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

     				if ($class in replacement)
     					icon.attr('class', 'ui-icon ' + replacement[$class]);
     			});
     		}

     		function enableTooltips(table) {
     			$('.navtable .ui-pg-button').tooltip({
     				container : 'body'
     			});
     			$(table).find('.ui-pg-div').tooltip({
     				container : 'body'
     			});
     		}

     		// var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

     		$(document).one('ajaxloadstart.page', function(e) {
     			$(grid_selector).jqGrid('GridUnload');
     			$('.ui-jqdialog').remove();
     		});
     		
     		jQuery(grid_selector).jqGrid('navButtonAdd', pager_selector,{
     			caption:"",
			    title : "新增兑换码",
     			buttonicon:"ui-icon ace-icon fa fa-plus-circle purple",
     			onClickButton: function(){
     				var ids = ['mod-add-redeemCode','mod-add-quantity','mod-add-remark'];
     				for(var i=0;i<ids.length;i++){
     					$('#' + ids[i]).val('');
     				}
     				$('#mod-add-expiryDate').datepicker('setDate', null);
     				getProductNames("mod-add-productName");
     				$("#mod-add").modal("toggle");
     			},
     			position:"last"
			}).jqGrid('navButtonAdd', pager_selector,{
     			caption:"",
			    title : "修改兑换码",
     			buttonicon:"ui-icon ace-icon fa fa-pencil blue",
     			onClickButton: function(){
     				var selectedIds = myGrid.jqGrid("getGridParam", "selarrrow");
     				if(selectedIds.length < 1){
     					showMsg('请选择记录');
     					return;
     				}
     				if(selectedIds.length > 1){
     					showMsg('只能选择一条记录');
     					return;
     				}
     				var rowData = myGrid.jqGrid('getRowData',selectedIds[0]);
     				getProductNames("mod-edit-productName");
     				$('#mod-edit-redeemCode').val(rowData.code);
     				$('#mod-edit-quantity').val(rowData.quantity);
     				$('#mod-edit-productName option:contains("' + rowData.productName + '")').attr("selected", "selected");
     				$('#mod-edit-expiryDate').datepicker('setDate', rowData.expiryDate);
     				$('#mod-edit-remark').val(rowData.remark);
     				$('#mod-edit-id').val(rowData.id);
     				$("#mod-edit").modal("toggle");
     			},
     			position:"last"
			});
     		
     		$("#mod-add-redeemCode-button").click(function(event) {
     			var code = getRedeemCode(4);
        		$('#mod-add-redeemCode').val(code);
			});
     		
     		$('#mod-add-expiryDate').datepicker({
		        language: 'zh-CN',
		        pickTime: false,
		        todayBtn: true,
		        autoclose: true,
		        minView: '2',
		        forceParse: false,
		        format:"yyyy-mm-dd"
		    });
     		$('#mod-add-expiryDate').datepicker("disable").attr("readonly","readonly");

     		$('#mod-edit-expiryDate').datepicker({
		        language: 'zh-CN',
		        pickTime: false,
		        todayBtn: true,
		        autoclose: true,
		        minView: '2',
		        forceParse: false,
		        format:"yyyy-mm-dd"
		    });
     		$('#mod-edit-expiryDate').datepicker("disable").attr("readonly","readonly");

     		$('#mod-add-submit').click(function(event) {
     			addRedeemCode();
			});

     		$('#mod-edit-submit').click(function(event) {
     			editRedeemCode();
			});
     	});
		
		//保存兑换码
		function addRedeemCode(){
			var redeemCode = $('#mod-add-redeemCode').val();
			if(redeemCode.length < 1){
				showMsg('兑换码不能为空');
				return;
			}else{
				if(redeemCode.length == 4){
					if(validateLetterAndNumber(redeemCode)){
						showMsg('兑换码只能为4位数字或字母');
						return;
					}
				}else{
					showMsg('兑换码只能为4位数字或字母');
					return;
				}
			}
			var quantity = $('#mod-add-quantity').val();
			if(quantity.length < 1){
				showMsg('使用次数不能为空');
				return;
			}
			var productId = $('#mod-add-productName').val();
			var expiryDate = $('#mod-add-expiryDate').val();
			if(expiryDate.length < 1){
				showMsg('有效期不能为空');
				return;
			}
			var remark = $('#mod-add-remark').val();
			var url = "${contextPath}/sys/redeem/add";
			var parameters = {"code":redeemCode,"expiryDate":expiryDate,"productId":productId,"quantity":quantity,"remark":remark};
    		postData(true, url, parameters, addRedeemCodeCallback, errorCallbackDefault);
		}
		
		function addRedeemCodeCallback(data){
			if(data.success){
 				$("#mod-add").modal("toggle");
				showMsg('保存成功');
				reloadGrid();
			}else{
    			showMsg(data.message);
    		}
		}
		
		//修改兑换码
		function editRedeemCode(){
			var quantity = $('#mod-edit-quantity').val();
			if(quantity.length < 1){
				showMsg('使用次数不能为空');
				return;
			}
			var productId = $('#mod-edit-productName').val();
			var expiryDate = $('#mod-edit-expiryDate').val();
			if(expiryDate.length < 1){
				showMsg('有效期不能为空');
				return;
			}
			var remark = $('#mod-edit-remark').val();
			var id = $('#mod-edit-id').val();
			var url = "${contextPath}/sys/redeem/edit";
			var parameters = {"expiryDate":expiryDate,"productId":productId,"quantity":quantity,"remark":remark,"id":id};
    		postData(true, url, parameters, editRedeemCodeCallback, errorCallbackDefault);
		}
		
		function editRedeemCodeCallback(data){
			if(data.success){
 				$("#mod-edit").modal("toggle");
				showMsg('保存成功');
				reloadGrid();
			}else{
    			showMsg(data.message);
    		}
		}

    	function errorCallbackDefault(data){
    		
    	}

    	//查询套餐名
    	function getProductNames(name){
    		currentProductName = name;
    		$("#" + name + " option").remove();
    		var url = "${contextPath}/sys/redeem/getProductNames";
    		postData(false, url, {}, getProductNamesCallback, errorCallbackDefault);
    	}
    	
    	function getProductNamesCallback(data){
    		if(data.success){
    			var obj = $("#" + currentProductName);
    			var names = data.names;
    			var isNotNull = false;
    			for(var i in names){
    				obj.append("<option value='"+i+"'>"+names[i]+"</option>");
    				isNotNull = true;
    			}
    			if(isNotNull){
    				$("#mod-add-productName option:first").prop("selected", 'selected'); 
    			}
    		}else{
    			showMsg(data.message);
    		}
    	}
    	
    	//生成兑换码
    	function getRedeemCode(len){
    		var code = '';
    		for(var i=0;i<len;i++){
    			code += numberAndLetters[Math.round(Math.random() * (numberAndLetters.length-1))];
    		}
    		return code;
    	}

    	//向后台请求数据
    	function postData(async, url, parameters, successCallback, errorCallback){
    		$.ajax({
    			async: async,
    		    type : "POST",
    		    url : url,
    		    data : parameters,
    		    dataType : "json",
    		    success : function(data) {
    		    	successCallback(data); 
    		    },
    		    error : function(data) {
    		    	errorCallback(data);
    		    }
    	    }); 
    	}
    	
    	function reloadGrid(){
    		myGrid.trigger("reloadGrid");
    	}
    	
    	//显示信息
    	function showMsg(msg){
    		if(msg != undefined && msg.length > 0){
    			alert(msg);
    		}
    	}
    	
    	//数字和字母验证
    	function validateLetterAndNumber(str){
    		var reg = new RegExp("^[A-Za-z0-9]+$");
    		return !reg.test(str);
    	}
	});
</script>