<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <th:block th:include="include :: header('积分兑换商品')"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
  <form class="form-horizontal m" id="form-exchange">
    <!-- 隐藏字段，用于传递用户ID和会员卡号 -->
    <input name="userId" th:value="${vipCard.userId}" type="hidden">
    <input name="cardId" th:value="${vipCard.id}" type="hidden">
    <input name="score" th:value="${vipCard.score}" type="hidden">

    <!-- 会员卡信息 -->
    <div class="col-xs-12">
      <div class="form-group">
        <label class="col-sm-3 control-label">会员卡号：</label>
        <div class="col-sm-8">
          <input name="displayCardNumber" th:value="${vipCard.id}" class="form-control" type="text" disabled>
        </div>
      </div>
    </div>
    <div class="col-xs-12">
      <div class="form-group">
        <label class="col-sm-3 control-label">当前积分：</label>
        <div class="col-sm-8">
          <input name="displayPoints" th:value="${vipCard.score}" class="form-control" type="text" disabled>
        </div>
      </div>
    </div>
    <!-- 商品列表 -->
    <div class="col-xs-12">
      <div class="form-group">
        <label class="col-sm-3 control-label">兑换商品：</label>
        <div class="col-sm-8">
          <select name="productId" class="form-control">
            <option value="">请选择商品</option>
            <option th:each="product : ${productList}" th:value="${product.id}" th:text="${product.goodsName} + ' - ' + ${product.goodsScore} + '积分'"></option>
          </select>
        </div>
      </div>
    </div>
    <div class="col-xs-12">
      <div class="form-group">
        <div class="col-sm-8 col-sm-offset-3">
          <button class="btn btn-primary" type="button" onclick="submitHandler()">兑换</button>
        </div>
      </div>
    </div>
  </form>
</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
  var prefix = ctx + "vipCard";
  $("#form-exchange").validate({
    focusCleanup: true
  });

  function submitHandler() {
    var productId = $('select[name="productId"]').val();
    if (!productId) {
      $.modal.alertWarning("请选择要兑换的商品！");
      return;
    }

    // 获取当前积分
    var currentPoints = parseFloat($('#form-exchange input[name="score"]').val());
    // 获取商品所需积分
    var productPoints = parseFloat($('select[name="productId"] option:selected').text().split(' - ')[1].replace('积分', ''));

    // 判断当前积分是否小于商品所需积分
    if (currentPoints < productPoints) {
      $.modal.alertError("积分不足，无法兑换该商品！");
      return;
    }

    //+ "&productId=" + productId
    var productPoints = $('select[name="productId"] option:selected').text().split(' - ')[1].replace('积分', '');
    var formData = $('#form-exchange').serialize()  + "&payScore=" + productPoints;
    $.operate.save(prefix + "/exchange", formData);
  }
</script>
</body>
</html>
