<template>
  <section class="content">
    <div class="box box-primary">
      <div class="box-body">
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1 id="itemTitle"></h1>
        </section>
        <div id="toolbar">
          <div class="col-sm-12">
            <label for="erbanNo"
                   class="col-sm-1 control-label">用户ID:</label>
            <div class="col-sm-2">
              <input type="number"
                     class="form-control"
                     name="erbanNo"
                     id="erbanNo">
            </div>
            <label for="gameId"
                   class="col-sm-1 control-label">游戏类型:</label>
            <div class="col-sm-2">
              <select name="gameId"
                      id="gameId"
                      class="form-control"></select>
            </div>
          </div>
          <div class="col-sm-12">
            <label for="startTime"
                   class="col-sm-1 control-label">添加日期:</label>
            <div class="col-sm-2">
              <input type="text"
                     class="input-sm form-control"
                     name="startTime"
                     id="startTime">
            </div>

            <label for="endTime"
                   class="col-sm-1 control-label">至:</label>
            <div class="col-sm-2">
              <input type="text"
                     class="input-sm form-control"
                     name="endTime"
                     id="endTime">
            </div>
          </div>
          <div class="col-sm-12">
            <button id="btnSearch"
                    class="btn btn-default">
              <i class="glyphicon glyphicon-search"></i>查询
            </button>
            <button id="btnAdd"
                    class="btn btn-default">
              <i class="glyphicon glyphicon-plus"></i>增加
            </button>
            <button id="btnBatchInvaild"
                    class="btn btn-danger">
              <i class="glyphicon glyphicon-remove"></i>批量失效
            </button>
          </div>
        </div>
      </div>

      <!-- .content -->
      <div id="table"></div>

    </div>
  </section>

  <div class="modal fade"
       id="userModal"
       tabindex="-1"
       role="dialog"
       aria-labelledby="modalLabel">
    <div class="modal-dialog"
         role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title"
              id="modalLabel">添加陪玩</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal"
                id="modalForm">
            <input type="hidden"
                   name="uid"
                   id="uid" />
            <div class="form-group">
              <label for="modalErbanNo"
                     class="col-sm-3 control-label">用户ID:</label>
              <div class="col-sm-9">
                <input type="number"
                       class="form-control validate[required]"
                       name="modalErbanNo"
                       id="modalErbanNo"
                       onchange="inputErbanNo(this)">
              </div>
            </div>
            <div class="form-group">
              <div class="col-sm-12">
                <input type="button"
                       class="form-control"
                       value="添加游戏"
                       id="modalAddBtn"
                       onclick="addGameInfo()" />
              </div>
            </div>
            <div id="modalGames"></div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button"
                  class="btn btn-default"
                  data-dismiss="modal">关闭</button>
          <button type="button"
                  class="btn btn-primary"
                  id="submit">确定</button>
        </div>

      </div>
    </div>
  </div>
</template>
<script>
import TableHelper from '@/utils/bootstrap-table-helper';

let modalData = {};
var gameInfoList = [];
var gameInfoMap = {};
export default {
  name: "UserGamePartnerInfoAdminView",
  setup () {
    function selectGameId (select, index) {
      const gameId = select.options[select.selectedIndex].value;
      const gameInfo = gameInfoMap[gameId];
      modalData.games[index] = { gameId: gameInfo.gameId, tags: Object.assign([], gameInfo.tags) }
      freshUserModal()
    }
    function inputErbanNo (input) {
      modalData.erbanNo = input.value;
    }
    function inputPrice (input, index) {
      modalData.games[index].price = input.value;
    }
    function inputProficiency (input, index) {
      modalData.games[index].proficiency = input.value;
    }
    function inputTag (input, index, tagIndex) {
      modalData.games[index].tags[tagIndex].tagVal = input.value;
    }
    function addGameInfo () {
      if (!modalData.games) {
        modalData.games = [];
      }
      const hasAddGameId = modalData.games.map(game => game.gameId);
      const gameInfo = gameInfoList.filter(gameInfo => !hasAddGameId.includes(gameInfo.gameId))[0];
      modalData.games.push({ gameId: gameInfo.gameId, tags: Object.assign([], gameInfo.tags) })
      freshUserModal()
    }
    window.selectGameId = selectGameId;
    window.inputErbanNo = inputErbanNo;
    window.inputPrice = inputPrice;
    window.inputProficiency = inputProficiency;
    window.inputTag = inputTag;
    window.addGameInfo = addGameInfo;
    return {
      selectGameId,
      inputErbanNo,
      inputPrice,
      inputProficiency,
      inputTag,
      addGameInfo,
    };
  },
  created () {
    this.$nextTick(function () {
      this.initData();
    });
  },
  methods: {
    initData () {
      $(function () {
        cacheGameInfo();
        $('#table').bootstrapTable('destroy');
        // 清空分页组件的容器
        $('.fixed-table-pagination').empty();
        $('#table').bootstrapTable({
          columns: [
            { field: 'checkBox', title: 'id', align: 'center', checkbox: true, width: '5%' },
            { field: 'erbanNo', title: '用户ID', align: 'center', width: '5%' },
            { field: 'nick', title: '昵称', align: 'center', width: '10%' },
            { field: 'games', title: '支持游戏', align: 'center', width: '60%', formatter: gameFormatter },
            { field: 'updateTime', title: '更新时间', align: 'center', width: '10%' },
            { field: 'adminName', title: '操作人', align: 'center', width: '10%' },
            { field: 'status', title: '状态', align: 'center', width: '5%', formatter: function (val) { return val ? '有效' : '无效'; } },
            {
              field: 'operate',
              title: '操作',
              align: 'center',
              width: '10%',
              formatter: function (val, row, index) {
                return '<button id="btnEdit" name="btnEdit" class="btn btn-sm opt-edit" data-id=' + row.uid + '>' +
                  '<i class="glyphicon glyphicon-edit"></i> 编辑</button>&nbsp;&nbsp;' +
                  (row.status ?
                    '<button class="btn btn-sm btn-danger opt-invaild" data-id=' + row.uid +
                    '><i class="glyphicon glyphicon-remove"></i>失效</button>'
                    :
                    '<button class="btn btn-sm btn-success opt-vaild" data-id=' + row.uid +
                    '><i class="glyphicon glyphicon-save"></i>生效</button>'
                  )
              }
            }
          ],
          uniqueId: 'uid',
          undefinedText: 0,
          cache: false,
          striped: true,
          showRefresh: false,
          pageSize: 20,
          pagination: true,
          pageList: [20, 50, 100],
          search: false,
          sidePagination: "server", //表示服务端请求
          queryParamsType: "undefined",
          queryParams: function queryParams (params) {   //设置查询参数
            var param = {
              pageNum: params.pageNumber,
              pageSize: params.pageSize,
              erbanNo: $('#erbanNo').val(),
              gameId: $('#gameId').val(),
              startTime: $('#startTime').val(),
              endTime: $('#endTime').val()
            };
            return param;
          },
          toolbar: '#toolbar',
          url: '/admin/gamePartner/user/page',
          onLoadSuccess: function () {  //加载成功时执行
            console.log("load success");
          },
          onLoadError: function () {  //加载失败时执行
            console.log("load fail");
          }
        });
        // 查询刷新
        $('#btnSearch').on('click', function () {
          TableHelper.doRefresh('#table');
        });
        var chargeStart = $('#startTime').datetimepicker({
          format: 'yyyy-mm-dd hh:ii:00',
          autoclose: true
        });
        var chargeEnd = $('#endTime').datetimepicker({
          format: 'yyyy-mm-dd hh:ii:00',
          autoclose: true
        });
        $("#btnBatchInvaild").click(function () {
          const row = $('#table').bootstrapTable('getSelections');
          if (!row || row.length < 1) {
            $("#tipMsg").text("未勾选任何用户");
            $("#tipModal").modal('show');
            return;
          }
          if (confirm("确认批量失效吗? ")) {
            const uidStr = row.map(row => row.uid).join(",");
            console.info(uidStr)
            $.ajax({
              type: 'post',
              url: "/admin/gamePartner/user/changeStatus",
              data: { uidStr: uidStr, status: 0 },
              success: function (json) {
                if (json.code === 200) {
                  $("#tipMsg").text("操作成功");
                  $("#tipModal").modal('show');
                } else {
                  $("#tipMsg").text("操作失败." + json.message);
                  $("#tipModal").modal('show');
                }
                TableHelper.doRefresh("#table");
                $("#userModal").modal('hide');
              }
            });
          }
        });
        //新建标签
        $("#btnAdd").click(function () {
          openUserModal()
        });
        $("#submit").click(function () {
          if ($("#modalForm").validationEngine('validate')) {
            $.ajax({
              type: "post",
              url: "/admin/gamePartner/user/save",
              data: JSON.stringify(modalData),
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              success: function (json) {
                if (json.code === 200) {
                  $("#tipMsg").text("保存成功");
                  $("#tipModal").modal('show');
                  TableHelper.doRefresh("#table");
                  $("#userModal").modal('hide');
                } else {
                  $("#tipMsg").text("保存失败." + json.message);
                  $("#tipModal").modal('show');
                }
              }
            });
          }
        });
        $("#table").on("click", '.opt-edit', function () {
          const id = $(this).attr("data-id");
          if (!id) {
            $("#tipMsg").text("id参数有误");
            $("#tipModal").modal('show');
            return;
          }
          const row = $('#table').bootstrapTable('getRowByUniqueId', id);
          openUserModal(row);
        });
        $("#table").on("click", '.opt-vaild', function () {
          const id = $(this).attr("data-id");
          if (!id) {
            $("#tipMsg").text("id参数有误");
            $("#tipModal").modal('show');
            return;
          }
          if (confirm("确认该用户生效吗? ")) {
            $.ajax({
              type: 'post',
              url: "/admin/gamePartner/user/changeStatus",
              data: { uidStr: id, status: 1 },
              success: function (json) {
                if (json.code === 200) {
                  $("#tipMsg").text("操作成功");
                  $("#tipModal").modal('show');
                } else {
                  $("#tipMsg").text("操作失败." + json.message);
                  $("#tipModal").modal('show');
                }
                TableHelper.doRefresh("#table");
                $("#userModal").modal('hide');
              }
            });
          }
        });
        $("#table").on("click", '.opt-invaild', function () {
          const id = $(this).attr("data-id");
          if (!id) {
            $("#tipMsg").text("id参数有误");
            $("#tipModal").modal('show');
            return;
          }
          if (confirm("确认该用户失效吗? ")) {
            $.ajax({
              type: 'post',
              url: "/admin/gamePartner/user/changeStatus",
              data: { uidStr: id, status: 0 },
              success: function (json) {
                if (json.code === 200) {
                  $("#tipMsg").text("操作成功");
                  $("#tipModal").modal('show');
                } else {
                  $("#tipMsg").text("操作失败." + json.message);
                  $("#tipModal").modal('show');
                }
                TableHelper.doRefresh("#table");
                $("#userModal").modal('hide');
              }
            });
          }
        });
      });

      function openUserModal (data) {
        clearUserModal();
        if (data) {
          setUserModal(data);
        }
        $("#userModal").modal('show');
      }
      function clearUserModal () {
        modalData = {};
        $("#modalErbanNo").val("");
        $("#modalGames").empty();
      }
      function setUserModal (data) {
        modalData = {
          uid: data.uid, erbanNo: data.erbanNo,
          games: Object.assign([], data.games ? data.games.map(game => { return { gameId: game.gameId, price: game.price, proficiency: game.proficiency, tags: Object.assign([], game.tags) } }) : [])
        };
        freshUserModal();
      }




      function cacheGameInfo () {
        $.ajax({
          type: 'get',
          url: '/admin/gamePartner/info/listAll',
          dataType: 'json',
          success: function (res) {
            if (res.code === 200) {
              const data = res.data;
              gameInfoList = data
              gameInfoList.forEach(gameInfo => gameInfoMap[gameInfo.gameId] = gameInfo);
              makeOption(data);
            }
          }
        })
      }
      function makeOption (data) {
        var str = '<option value=""></option>';
        for (var i = 0; i < data.length; i++) {
          str += '<option value="' + data[i].gameId + '">' + data[i].gameName + '</option>';
        }
        $('#gameId').html(str);
      }
      function gameFormatter (val) {
        var str = ''
        if (!val || val.size < 1) {
          return str;
        }
        str += '<table>'
        val.forEach((game, gameIndex) => {
          if (gameIndex % 2 === 0) {
            str += '<tr>'
          }
          str += '<td width="50%"><table style="border-collapse:separate; border-spacing:5px 5px;">'
          str += ('<tr><td width="24%"><b>' + game.gameName + '</b></td><td width="24%">价格: ' + game.price + '</td><td width="24%">熟练度: ' + game.proficiency + '</td><td width="24%">接单次数: ' + game.finishNum + '</td></tr>');
          game.tags.forEach((tag, index) => {
            if (index / 3 === 0) {
              str += '<tr>'
            }
            str += ('<td width="33%" style="word-break: break-all;word-wrap: break-word;">' + tag.tagName + ': ' + tag.tagVal + '</td>');
            if ((index / 3 > 0 && index % 2 === 0) || index === (game.tags.size - 1)) {
              str += '</tr>'
            }
          })
          str += '</table></td>'
          if ((gameIndex / 2 > 0 && (gameIndex + 1) % 2 === 0) || gameIndex === (val.size - 1)) {
            str += '</tr>'
          }
        })
        str += '</table>'
        return str;
      }
    }
  }
};

function freshUserModal () {
  $("#modalUid").val(modalData.uid ?? "");
  $("#modalErbanNo").val(modalData.erbanNo ?? "");
  const hasAddGameId = modalData.games ? modalData.games.map(game => game.gameId) : [];
  const canAdd = gameInfoList.filter(gameInfo => !hasAddGameId.includes(gameInfo.gameId)).length !== 0;
  if (canAdd) {
    $("#modalAddBtn").show();
  } else {
    $("#modalAddBtn").hide();
  }
  const gameStr = !modalData.games ? '' : modalData.games.map((game, index) =>
    '<div class="form-group">' +
    '<label for="modalGameId" class="col-sm-3 control-label">游戏:</label>' +
    '<div class="col-sm-9">' +
    '<select name="type" name="modalGameId" class="form-control validate[required]" onchange="selectGameId(this,' + index + ')">' +
    gameInfoList.map(gameInfo =>
      '<option value="' + gameInfo.gameId + '" ' + (game.gameId === gameInfo.gameId ? 'selected' : '') + '>' + gameInfo.gameName + '</option>')
      .join("") +
    '</select>' +
    '</div>' +
    '</div>' +
    '<div class="form-group">' +
    '<label for="modalPrice" class="col-sm-3 control-label">单价:</label>' +
    '<div class="col-sm-9">' +
    '<input type="number" class="form-control validate[required]" name="modalPrice" onchange="inputPrice(this, ' + index + ')" value="' + (game.price ?? 0) + '">' +
    '</div>' +
    '</div>' +
    '<div class="form-group">' +
    '<label for="modalProficiency" class="col-sm-3 control-label">熟练度:</label>' +
    '<div class="col-sm-9">' +
    '<input type="text" class="form-control validate[required]" name="modalProficiency" onchange="inputProficiency(this, ' + index + ')" value="' + (game.proficiency ?? '') + '">' +
    '</div>' +
    '</div>' +
    game.tags.map((tag, tagIndex) =>
      '<div class="form-group">' +
      '<label for="modalTag" class="col-sm-3 control-label">' + tag.tagName + ':</label>' +
      '<div class="col-sm-9">' +
      '<input type="text" class="form-control validate[required]" name="modalTag" onchange="inputTag(this, ' + index + ',' + tagIndex + ')" value="' + (tag.tagVal ?? '') + '">' +
      '</div>' +
      '</div>'
    ).join("")
  ).join("<hr>");
  $("#modalGames").html(gameStr);
}
</script>

