<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('会员码管理')" />
</head>
<body class="gray-bg">
	<div class="container-div">
		<div class="row">
			<div class="btn-group-sm" id="toolbar" role="group">
				<a id="btnCreateMemberCode" class="btn btn-success" href="javascript:void(0)" onclick="openCreateModal()" shiro:hasPermission="adam:member:code:creation">
					<i class="fa fa-plus"></i> 创建
				</a>
			</div>

			<div class="col-sm-12 select-table table-striped">
				<table id="bootstrap-table"></table>
			</div>

			<div id="member-gencode-form" class="modal fade" aria-hidden="true">
				<div class="modal-dialog" style="width:33%;">
					<div class="modal-content modal-body row">
						<h3 class="m-t-none m-b text-center">创建会员码</h3>

						<form role="form" id="form-member-code-generate">
							<input name="memberId" type="hidden" th:value="${memberId}" readonly>
							<div class="form-group">
								<label>兑换套餐：</label>
								<!-- 不用 select2：动态 option 会被 select2 吃掉只剩一条 -->
								<select name="memberPriceId" id="memberPriceId" class="form-control noselect2" required>
									<option value="">加载中...</option>
								</select>
								<p class="help-block m-b-none text-muted" style="margin-top:6px;">兑换后按所选价格包天数开会员，并发放该档权益</p>
							</div>
							<div class="form-group">
								<label>生产数量：</label>
								<input type="text" name="genNum" class="form-control" placeholder="请输入生产数量（1-100）" maxlength="3">
							</div>
							<div class="form-group">
								<label>备注描述：</label>
								<textarea rows="3" name="detail" placeholder="请输入备注描述" class="form-control"></textarea>
							</div>
							<div class="text-center" style="margin-bottom: -15px;margin-top: 10px;">
								<button class="btn btn-sm btn-primary m-t-n-xs" type="button" onclick="memberCodeGenerate()">
									<strong>确认创建</strong>
								</button>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
<th:block th:include="include :: footer" />
<script th:inline="javascript">
	var viewMemberCodeListFlg = [[${@permission.hasPermi('adam:member:code:list')}]];
	var memberId = [[${memberId}]];
	var prefix = ctx + "adam/mcode";
	var onlinePriceList = [];

	$(function() {
		var options = {
			url: prefix + "/mgt/list",
			createUrl: prefix + "/mgt/creation/{id}",
			exportUrl: prefix + "/export_code",
			detailUrl: ctx + "adam/order/orderList/detail/{id}",
			sortName: "createdAt",
			sortOrder: "desc",
			modalName: "会员码创建记录",
			queryParams: function (params) {
				return {
					pageSize: params.limit,
					pageNum: params.offset / params.limit + 1,
					searchValue: params.search,
					orderByColumn: params.sort,
					isAsc: params.order,
					memberId: memberId
				};
			},
			columns: [{
				checkbox: true
			},
				{
					field: 'memberName',
					title: '会员名称',
					width: 180
				},
				{
					field: 'memberCombo',
					title: '兑换套餐',
					width: 200
				},
				{
					field: 'memberPriceId',
					title: '价格包ID',
					width: 140
				},
				{
					field: 'genNum',
					title: '生产数量',
					width: 80
				},
				{
					field: 'useNum',
					title: '使用数量',
					width: 80
				},
				{
					field: 'detail',
					title: '备注',
					width: 220
				},
				{
					field: 'operator',
					title: '创建人',
					width: 100
				},
				{
					field: 'createdAt',
					title: '创建时间',
					width: 150,
					formatter: function (value, row, index) {
						return $.common.sprintf("<span>%s</span>", null != value ? value.replace("T"," ").substring(0, 19) : value);
					}
				},
				{
					title: '操作',
					align: 'center',
					formatter: function(value, row, index) {
						var actions = [];
						actions.push('<a class="btn btn-primary btn-xs ' + viewMemberCodeListFlg + '" href="javascript:void(0)" onclick="memberCodeList(\'' + row.batchNo + '\')"><i class="fa fa-list-ul"></i>查看码列表</a> ');
						return actions.join('');
					}
				}]
		};
		$.table.init(options);
		// 打开列表页就拉套餐
		reloadOnlinePrices();
	});

	function memberCodeList(batchNo) {
		$.modal.openTab("会员码列表", prefix + '/mgt/code?batchNo=' + batchNo);
	}

	$("#form-member-code-generate").validate({
		onkeyup: false,
		rules:{
			memberPriceId: {
				required: true
			},
			genNum: {
				required: true,
				number: true,
				min: 1,
				max: 100
			},
			detail: {
				required: true,
				minlength: 2,
				maxlength: 100
			}
		},
		messages: {
			memberPriceId: {
				required: "请选择兑换套餐"
			},
			genNum: {
				required: "请输入生产数量",
				number: "生产数量必须为数字",
				min: "生产数量不能小于1",
				max: "生产数量不能大于100"
			},
			detail: {
				required: "请输入备注描述",
				minlength: "备注描述不得少于2个字符",
				maxlength: "备注描述不得大于100个字符"
			}
		},
		focusCleanup: true
	});

	function fillPriceOptions(list) {
		onlinePriceList = list || [];
		var $sel = $('#memberPriceId');
		$sel.empty();
		if (!onlinePriceList.length) {
			$sel.append($('<option></option>').val('').text('暂无上线价格包'));
			$('#btnCreateMemberCode').addClass('disabled');
			return;
		}
		// 默认不选中：合上时不会误以为只有年卡一条；点开可见全部上线档
		$sel.append($('<option></option>').val('').text('请选择兑换套餐（共' + onlinePriceList.length + '档）'));
		$.each(onlinePriceList, function (i, mp) {
			var text = (mp.name || '未命名') + ' · ' + (mp.days != null ? mp.days : '-') + '天 · ¥' + (mp.price != null ? mp.price : '-');
			$sel.append($('<option></option>').attr('value', mp.memberPriceId).text(text));
		});
		$('#btnCreateMemberCode').removeClass('disabled');
		console.log('[member-code] online prices:', onlinePriceList.length, onlinePriceList);
	}

	function reloadOnlinePrices(done) {
		$.ajax({
			url: prefix + '/mgt/prices',
			type: 'get',
			data: { memberId: memberId },
			dataType: 'json',
			success: function (res) {
				var list = (res && res.code == web_status.SUCCESS && res.data) ? res.data : [];
				fillPriceOptions(list);
				if (typeof done === 'function') {
					done(list);
				}
			},
			error: function () {
				fillPriceOptions([]);
				$.modal.msgWarning("加载兑换套餐失败，请刷新页面重试");
				if (typeof done === 'function') {
					done([]);
				}
			}
		});
	}

	function openCreateModal() {
		if ($('#btnCreateMemberCode').hasClass('disabled')) {
			$.modal.alertWarning("暂无上线价格包，请先在会员套餐中配置并上线");
			return;
		}
		reloadOnlinePrices(function (list) {
			if (!list.length) {
				$.modal.alertWarning("暂无上线价格包，请先在会员套餐中配置并上线");
				return;
			}
			$('#member-gencode-form').modal('show');
		});
	}

	function memberCodeGenerate() {
		if (!$('#memberPriceId').val()) {
			$.modal.alertWarning("请选择兑换套餐");
			return;
		}
		if ($.validate.form("form-member-code-generate")) {
			$('#member-gencode-form').modal('hide');
			$.operate.saveModal(prefix + "/mgt/creation", $('#form-member-code-generate').serialize(), memberCodeGenerateCallback);
		}
	}
	function memberCodeGenerateCallback(result) {
		if (result.code == web_status.SUCCESS) {
			$.modal.alertSuccess(result.msg);
			setTimeout("refreshTab()", 1500);
		} else if (result.code == web_status.WARNING) {
			$('#member-gencode-form').modal('show');
			$.modal.alertWarning(result.msg);
		} else {
			$('#member-gencode-form').modal('show');
			$.modal.alertError(result.msg);
		}
	}
</script>
</body>
</html>
