<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>欢迎页面-X-admin2.0</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
        <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
        <link rel="stylesheet" href="./static/css/font.css">
        <link rel="stylesheet" href="./static/css/xadmin.css">
        <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
        <script src="./static/lib/layui/layui.js" charset="utf-8"></script>
        <script type="text/javascript" src="./static/js/xadmin.js"></script>
    </head>
    <body>
    <input type="text" id="token" value={{.token}} hidden=true>
    <div class="x-body layui-anim layui-anim-up">
        <blockquote class="layui-elem-quote">
          <input class="layui-btn" type="button" onclick="OpenAddItem()" value=新增>
              
          <input class="layui-btn" type="button" onclick="Refresh()" value=刷新>
        </blockquote>
    </div>

    <dialog open id="modalAdd" class="x-body layui-anim layui-anim-up" hidden=true style = "center;">
        <form action="exchangecode" method="post" class="layui-form layui-form-pane">
            兑换码
            <input id="pcode" name="pcode" placeholder="兑换码"  type="text" lay-verify="required" class="layui-input">
            <br>
            <input class="layui-btn" type="button" onclick="randCode()" value=随机>
            <hr class="hr15">
            可领次数
            <input id="awardTimes" name="awardTimes" placeholder="剩余领奖次数"  type="text" lay-verify="required" class="layui-input">
            <br>
            过期时间
            <input id="expireTime" name="expireTime" placeholder="过期时间"  type="text" lay-verify="required" class="layui-input">
            <br>
            随机物品列表
            <br>
            <hr class="hr15">
            <table class="radio-table" border="1" id="tb_item">
              <thead>
                <th style="width:100px;">物品ID</th>
                <th style="width:100px;">物品数量</th>
                <th style="width:100px;">权重</th>
                <th style="width:256px;">操作</th>
              </thead>
            </table>
            <br>
            <input class="layui-btn" type="button" onclick="modalAddItem()" value=新增道具>
            <hr class="hr15">
            <input value="新增" class="layui-btn" style="width:100%;" type="button" onclick="addExchangeCode()">
            <br>
            <br>
            <input value="关闭" class="layui-btn" style="width:100%;" type="button" onclick="closeModalAdd()">
            <hr class="hr20" >
        </form>
    </dialog>

    <dialog open id="modalModify" class="x-body layui-anim layui-anim-up" hidden=true style = "center;">
        <form action="exchangecode" method="put" class="layui-form layui-form-pane">
            <input id="pcode_modify" hidden=true type="text">
            剩余领奖次数
            <input id="awardTimes_modify" name="awardTimes_modify" placeholder="剩余领奖次数"  type="text" lay-verify="required" class="layui-input">
            <br>
            过期时间
            <input id="expireTime_modify" name="expireTime_modify" placeholder="过期时间"  type="text" lay-verify="required" class="layui-input">
            <hr class="hr15">
            随机物品列表
            <table class="radio-table" border="1" id="tb_item_modify">
              <thead>
                <th style="width:100px;">物品ID</th>
                <th style="width:100px;">物品数量</th>
                <th style="width:100px;">权重</th>
                <th style="width:256px;">操作</th>
              </thead>
            </table>
            <br>
            <input class="layui-btn" type="button" onclick="modalAddItem()" value=新增道具>
            <hr class="hr15">
            <input value="修改" class="layui-btn" style="width:100%;" type="button" onclick="modifyExchangeCode()">
            <br>
            <br>
            <input value="关闭" class="layui-btn" style="width:100%;" type="button" onclick="closeModalModify()">
            <hr class="hr20" >
        </form>
    </dialog>
    <dialog open id="modalItem" class="x-body layui-anim layui-anim-up" hidden=true style = "center;">
        <form class="layui-form layui-form-pane">
            <select name="" id="item_id" onchange="gradeItemChange(this.options[this.options.selectedIndex].value)">
              {{range .ItemList}}
                <option value={{.Id}}>{{.Name}}</option>
              {{end}}
            </select>
            <br>
            <input id="item_count" name="item_count" placeholder="物品数量"  type="number" lay-verify="required" class="layui-input">
            <br>
            <input id="weight" name="weight" placeholder="随机权重"  type="number" lay-verify="required" class="layui-input">
            <hr class="hr15">
            <input id="btn" value="新增" class="layui-btn" style="width:100%;" type="button" onclick="addItem()">
            <br>
            <br>
            <input value="关闭" class="layui-btn" style="width:100%;" type="button" onclick="closeModalItem()">
            <hr class="hr20" >
        </form>
    </dialog>
    <table class="radio-table" border="1">
      <thead>
        <th style="width:256px;">操作</th>
        <th style="width:64px;">兑换码</th>
        <th style="width:128px;">剩余领奖次数</th>
        <th style="width:256px;">创建时间</th>
        <th style="width:256px;">修改时间</th>
        <th style="width:256px;">过期时间</th>
        <th style="width:256px;">随机奖励列表</th>
      </thead>
      <tbody>
        {{range .infoList}}
          <tr>
            <td style = "text-align:center;">
              <input class="layui-btn" type="button" onclick="OpenModifyItem({{.Pcode}}, {{.AwardTimes}}, {{.ExpireTime}}, {{.Items}})" value=修改>
              {{"   | "}}
              <input class="layui-btn" type="button" onclick="clickDelete({{.Pcode}})" value=删除>
            </td>
            <td style = "text-align:center;">{{.Pcode}}</td>
            <td style = "text-align:center;">{{.AwardTimes}}</td>
            <td style = "text-align:center;">{{TimeToStr .CreateTime}}</td>
            <td style = "text-align:center;">{{TimeToStr .ModifyTime}}</td>
            <td style = "text-align:center;">{{TimeToStr .ExpireTime}}</td>
            <td style = "text-align:center;">{{WeightItems .Items}}</td>
          </tr>
        {{end}}
      </tbody>
    </table>
    <script language="JavaScript">
      function formaData(timer) {
          const year = timer.getFullYear()
          const month = (timer.getMonth() + 1).toString().padStart(2, '0') // 由于月份从0开始，因此需加1
          const day = timer.getDate().toString().padStart(2, '0')
          const hour = timer.getHours().toString().padStart(2, '0')
          const minute = timer.getMinutes().toString().padStart(2, '0')
          const second = timer.getSeconds().toString().padStart(2, '0')
          return `${(year)}-${(month)}-${(day)} ${(hour)}:${(minute)}:${(second)}`
      }
      var randChats = ['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'];
      function generateMixed(n) {
          var res = "";
          for(var i = 0; i < n ; i ++) {
              var id = Math.ceil(Math.random()*(randChats.length-1));
              res += randChats[id];
          }
          return res;
      }

      // 刷新页面
      function Refresh() {
        var token = document.getElementById("token").value;
        var text = "token=" + encodeURI(token);

        $.ajax({
          type:"get",
          url:"/exchangecode?" + text,
          success:function (data) {
            // alert(data.status);
            window.location.href="/exchangecode";
          }
        });
      }
      var isModelAdd = true
      var codeItems = [];
      // 刷新物品列表
      function refreshTableItem() {
        var key = "tb_item"
        if (isModelAdd == false){key = "tb_item_modify"}
        var obj = document.getElementById(key)
        var tbody = obj.getElementsByTagName("tbody")[0];
        if (tbody) {
          if (-[1,]) {
            obj.removeChild(tbody);
          }else{
            obj.removeNode(tbody);
          }
        }

        if (codeItems.length > 0 && codeItems[0] != "") {
          tbody = document.createElement("tbody")
          for (var i = 0; i < codeItems.length; i++){
            var tr = document.createElement("tr")

            var td1 = document.createElement("td")
            td1.style = "text-align:center;"
            td1.innerHTML = codeItems[i].id
            tr.appendChild(td1)

            var td2 = document.createElement("td")
            td2.style = "text-align:center;"
            td2.innerHTML = codeItems[i].count
            tr.appendChild(td2)

            var td3 = document.createElement("td")
            td3.style = "text-align:center;"
            td3.innerHTML = codeItems[i].weight
            tr.appendChild(td3)

            var td4 = document.createElement("td")
            td4.style = "text-align:center;"
            td4.innerHTML = '<input class="layui-btn" type="button" onclick="itemDelete(' + codeItems[i].id + ')" value=删除>'
            tr.appendChild(td4)

            tbody.appendChild(tr)
          }
          obj.appendChild(tbody)
        }
      }
      // 物品弹窗
      function modalAddItem() {
        refreshTableItem()

        document.getElementById("modalItem").hidden = false;
      }
      function closeModalItem() {
        document.getElementById("modalItem").hidden = true;
      }
      function addItem() {
        var item_id = parseInt(document.getElementById("item_id").value);
        var item_count = parseInt(document.getElementById("item_count").value);
        var weight = parseInt(document.getElementById("weight").value);
        console.log("addItem weight:"+weight)

        if (item_id == null || item_id == 0){
          alert("请选择道具");
          return;
        }
        if (item_count == null || item_count <= 0){
          alert("道具数量不能为空或负数");
          return;
        }
        if (weight == null || weight <= 0){
          alert("权重值错误！");
          return;
        }

        var isMatch = false
        for (var i = 0; i < codeItems.length; i ++) {
          if (codeItems[i].id == item_id) {
            isMatch = true;
            codeItems[i].count += item_count;
            break
          }
        }
        if (isMatch == false) {
          codeItems.push({'id':item_id, 'count':item_count, 'weight':weight})
        }
        refreshTableItem()
        document.getElementById("modalItem").hidden = true;
      }
      // 删除物品
      function itemDelete(itemId) {
        var id = parseInt(itemId)
        console.log("itemDelete itemId:" + itemId)
        for (var i = 0; i < codeItems.length; i ++) {
          if (codeItems[i].id == id) {
            console.log("itemDelete 找到道具")
            codeItems.splice(i, 1)
            break
          }
        }
        refreshTableItem()
        document.getElementById("modalItem").hidden = true;
      }

      // 随机兑换码
      function randCode() {
        document.getElementById("pcode").value = generateMixed(6);
      }
      function OpenAddItem() {
        isModelAdd = true
        document.getElementById("pcode").value = generateMixed(6);
        document.getElementById("awardTimes").value = 100;

        var dateTime = new Date();
        dateTime = dateTime.setDate(dateTime.getDate()+30);
        dateTime = new Date(dateTime);
        document.getElementById("expireTime").value = formaData(dateTime);

        document.getElementById("modalAdd").hidden = false;
      }
      function closeModalAdd() {
        document.getElementById("modalAdd").hidden = true;
      }
      function addExchangeCode () {
        var token = document.getElementById("token").value;
        var pcode = document.getElementById("pcode").value;
        var awardTimes = parseInt(document.getElementById("awardTimes").value);
        var expireTime = document.getElementById("expireTime").value;

        if (pcode.length != 6){
          alert("兑换码长度错误！6位大写字母");
          return;
        }
        // 兑换码字符检查
        for (var i = 0; i < pcode.length; i ++){
          var isMatch = false
          for (var j = 0; j < randChats.length; j ++) {
            if (pcode[i] == randChats[j]){
              console.info("兑换码字符检查 i:"+i+";"+pcode[i])
              console.info("兑换码字符检查 j:"+j+";"+randChats[j])
              isMatch = true;
              break;
            }
          }
          if (isMatch == false){
            alert("兑换码错误！请使用大写字母");
            return;
          }
        }

        if (awardTimes <= 0){
          alert("请正确设置领奖次数");
          return;
        }
        if (codeItems.length <= 0){
          alert("奖励物品空！");
          return;
        }
        // var items = ""
        // for (var i = 0; i < codeItems.length; i ++) {
        //   if (items != "") {
        //     items += "|";
        //   }
        //   items += codeItems[i].id + "," + codeItems[i].count + "," + codeItems[i].weight
        // }

        var text = "token=" + encodeURI(token);
        text += "&pcode=" + encodeURI(pcode);
        text += "&awardTimes=" + encodeURI(awardTimes);
        text += "&expireTime=" + encodeURI(expireTime);
        text += "&items=" + encodeURI(JSON.stringify(codeItems));

        $.ajax({
          type:"post",
          url:"/exchangecode?" + text,
          success:function (data) {
            // alert(data.status);
            if (data.status){
              window.location.href="/exchangecode";
              if (data.info){
                layer.msg(data.info,{icon:1,time:1000});
              }
            }else{
              if (data.info){
                alert(data.info);
              }else{
                window.location.href="/accountlogin";
              }
            }
          }
        });
      }

      function closeModalItem() {
        document.getElementById("modalItem").hidden = true;
      }

      function OpenModifyItem(pcode, awardTimes, expireTime, items) {
        isModelAdd = false;

        codeItems = []
        for (var i = 0; i < items.length; i ++) {
          codeItems.push({'id':items[i].id, 'count':items[i].count, 'weight':items[i].weight});
        }

        document.getElementById("pcode_modify").value = pcode;
        document.getElementById("awardTimes_modify").value = awardTimes;
        var dateTime = new Date(expireTime*1000);
        document.getElementById("expireTime_modify").value = formaData(dateTime);
        refreshTableItem()

        document.getElementById("modalModify").hidden = false;
      }
      function closeModalModify() {
        document.getElementById("modalModify").hidden = true;
      }

      function modifyExchangeCode () {
        var token = document.getElementById("token").value;
        var pcode = document.getElementById("pcode_modify").value;
        var awardTimes = document.getElementById("awardTimes_modify").value;
        var expireTime = document.getElementById("expireTime_modify").value;

        var text = "token=" + encodeURI(token);
        text += "&pcode=" + encodeURI(pcode);
        text += "&awardTimes=" + encodeURI(awardTimes);
        text += "&expireTime=" + encodeURI(expireTime);
        text += "&items=" + encodeURI(JSON.stringify(codeItems));

        $.ajax({
          type:"put",
          url:"/exchangecode?" + text,
          success:function (data) {
            // alert(data.status);
            if (data.status){
              window.location.href="/exchangecode";
              if (data.info){
                layer.msg(data.info,{icon:1,time:1000});
              }
            }else{
              if (data.info){
                alert(data.info);
              }else{
                window.location.href="/accountlogin";
              }
            }
          }
        });
      }

      function clickDelete (pcode) {
        var token = document.getElementById("token").value;
        var text = "token=" + encodeURI(token);
        text += "&pcode=" + encodeURI(pcode);

        $.ajax({
          type:"delete",
          url:"/exchangecode?" + text,
          success:function (data) {
            // alert(data.status);
            if (data.status){
              window.location.href="/exchangecode";
              if (data.info){
                layer.msg(data.info,{icon:1,time:1000});
              }
            }else{
              if (data.info){
                alert(data.info);
              }else{
                window.location.href="/accountlogin";
              }
            }
          }
        });
      }
    </script>
    </body>
</html>