<template>
  <div class=content>
    <div class="container">

      <div class="fck">
        <form id="search-form" class="search-form" @submit.prevent="onSubmit">
          <div class="form-group" v-bind:class="{ 'has-error': hasError}">
            <label class="control-label" for="searchText" v-if="hasError">{{lang.battle.notfound}}</label>
            <div class="input-group">
              <div class="input-group-addon"><span><i class="glyphicon glyphicon-search"></i></span></div>
              <input class="form-control" type="text" id="searchText" v-model="searchText"
                :placeholder="lang.battle.ph2">
              <div class="input-group-btn">
                <button class="btn btn-default" type="submit">{{lang.battle.search}}</button>
                <button class="btn btn-default" style="display:none" type="submit"
                  id="search">{{lang.battle.search}}</button>
              </div>
            </div>
          </div>
        </form>
      </div>

      <ul class="nav nav-tabs">
        <li class="active"><a href="#tab-1" role="tab" data-toggle="tab">{{lang.userRank.pointRank}} </a></li>
        <li><a href="#tab-2" role="tab" data-toggle="tab">{{lang.userRank.expRank}} </a></li>
      </ul>

      <div class="tab-content">

        <div role="tabpanel" class="tab-pane active" id="tab-1">
          <br>
          <!--<p>{{lang.userRank.tableHead2}}</p>-->
          <p>{{labelone}}<a href="https://bbs.ygobbs2.com/t/83049" target="_blank">竞技匹配积分&长期活动详解</a></p>
          <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
            <table class="table table-striped table-bordered table-hover example" id="pt_table" :width="width"></table>
          </div>
        </div>

        <div role="tabpanel" class="tab-pane" id="tab-2">
          <br>
          <p>{{lang.userRank.tableHead1}}</p>
          <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
            <table class="table table-striped table-bordered table-hover example" id="exp_table" :width="width"></table>
          </div>
        </div>

        <div class="form-group" style="display:none">
          <button type="submit" id="search" class="form-control btn btn-primary">{{lang.search}}</button>
        </div>

        <Footads></Footads>
      </div>
    </div>
  </div>
</template>

<script>
  import Footads from './Footads'
  import tb_language from './tb_lang.js'
  import API from '../api';
  import {
    mapGetters
  } from 'vuex'
  const placeholder='请输入用户名..'
  var expTable, ptTable
  export default {
    components: {
      Footads
    },
    created: function() {
      var regex_match =
        /(nokia|iphone|android|motorola|^mot-|softbank|foma|docomo|kddi|up.browser|up.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte-|longcos|pantech|gionee|^sie-|portalmmm|jigs browser|hiptop|^benq|haier|^lct|operas*mobi|opera*mini|320x320|240x320|176x220)/i;
      var u = navigator.userAgent;
      if (null == u) {
        return true;
      }
      var result = regex_match.exec(u);
      if (null == result) {} else {
        this.width = "250%"
      }
      var lang = localStorage.getItem('lang') || 'cn';
      this.init(lang)
      API.getLabel({}).then((res) => {
        this.labelone = res.data.text;
      }, (res) => {})
    },
    data() {
      return {
        placeholder,
        width: "100%",
        searchText: "",
        hasError: false,
        username: "",
        labelone: "",
      }
    },
    watch: {
      lang: function(val) {
        console.log('lang change1', val)
        this.init2()
      },
    },
    mounted: function() {
      this.init2();

    },
    computed: {
      ...mapGetters({
        lang: 'getLang',
      }),
    },
    methods: {
      init: function(lang) {},
      onSubmit: function() {
        var url = `#/userinfo?username=${encodeURIComponent(this.searchText)}`
        window.location.href = url
      },
      init2: function() {
        function renderPage() {
          if (ptTable) {
            ptTable.destroy();
          }
          if (expTable) {
            expTable.destroy();
          }
          expTable = renderExpTable();
          ptTable = renderArenaTable();
          API.getUsers({
            o: 'pt'
          }).then((res) => {
            if (ptTable) {
              ptTable.destroy();
            }
            ptTable = renderArenaTable(res.data)
          }, (res) => {
            console.log(res)
          });
          API.getUsers({
            o: 'exp'
          }).then((res) => {
            if (expTable) {
              expTable.destroy();
            }
            expTable = renderExpTable(res.data)
          }, (res) => {
            console.log(res)
          });
          $('#exp_table').onPostBody = function() {
            $('.search .search-input').attr('placeholder', '请输入要查找的名称');
          }
        }

        function renderArenaTable(tableData) {
          tableData = tableData || [];
          var lang = localStorage.getItem('lang') || 'cn';
          var rank = 1;
          var processData = tableData.map(function (d) {
            let ratio = 0
            if (d.athletic_all > 0) {
              ratio = (d.athletic_win / d.athletic_all * 100).toFixed(2)
            }
            var iconSrc = 'https://sapi.moecube.com:444/avatar/avatar/' + d.username + '/100/pic.png';
            return [rank++, iconSrc, String(d.username), parseInt(d.pt), d.athletic_win, d.athletic_lose, ratio + "%"];
          });
          var table = $('#pt_table').DataTable({
            "autoWidth": false,
            data: processData,
            pageLength: 25,
            order: [
              [0, "asc"]
            ],
            "ordering": true,
            columns: [
              {
                title: tb_language[lang].rank,

              },
              {
                title: tb_language[lang].name, // Display icon + username in this column

                render: function (data, type, row) {
                  var iconSrcWithUsername = row[1]; // 获取图像链接
                  var username = row[2]; // 获取用户名
                  return '<div style="display: flex; align-items: center;">' +
                      '<img src="' + iconSrcWithUsername + '" style="width: 35px; height: 35px; margin-right: 3px;"> ' +
                      '<a href="#/userinfo?username=' + encodeURIComponent(username) + '">' + username + '</a>' +
                      '</div>';
                },
              },
              {
                visible: false, // Hide the username column,

              },
              {
                title: tb_language[lang].pt,

              },
              {
                title: tb_language[lang].win,

              },
              {
                title: tb_language[lang].lose,

              },
              {
                title: tb_language[lang].wl,

              },
            ],
            "columnDefs": [{
              "render": function (data, type, row) {
                return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'>" + data + "</a>";
              },
              "targets": 2
            },],
            "language": tb_language[lang],
          });
          $(".input-sm").attr("placeholder", placeholder)

          return table;
        }

        function renderExpTable(tableData) {
          tableData = tableData || [];
          var lang = localStorage.getItem('lang') || 'cn';
          var rank = 1;
          var processData = tableData.map(function (d) {
            var iconSrc = 'https://sapi.moecube.com:444/avatar/avatar/' + d.username + '/100/pic.png';
            return [rank++, iconSrc, String(d.username), parseInt(d.exp), d.entertain_win, d.entertain_lose];
          });

          var table = $('#exp_table').DataTable({
            data: processData,
            pageLength: 25,
            order: [[0, "asc"]],
            "ordering": true,
            columns: [
              {
                title: tb_language[lang].rank
              },
              {
                title: tb_language[lang].name, // Display icon + username in this column
                render: function (data, type, row) {
                  var iconSrcWithUsername = row[1]; // 获取图像链接
                  var username = row[2]; // 获取用户名
                  return '<div style="display: flex; align-items: center;"><img src="' + iconSrcWithUsername + '" style="width: 35px; height: 35px; margin-right: 3px;"> <a href="#/userinfo?username=' + encodeURIComponent(username) + '">' + username + '</a></div>';
                },
              },
              {
                visible: false, // Hide the username column
              },
              {
                title: tb_language[lang].exp
              },
              {
                title: tb_language[lang].win
              },
              {
                title: tb_language[lang].lose
              },
            ],
            "columnDefs": [
              {
                "targets": [0, 3, 4, 5], // Target other columns (exp, win, lose) to make them non-orderable
                "orderable": false
              },
            ],
            "language": lang === 'en' ? tb_language.en : tb_language.cn,
          });
          $(".input-sm").attr("placeholder", placeholder);
          return table;
        }
        renderPage();
        $("#search").click(function() {
          renderPage();
          return false;
        })




      }
    },
    events: {
      'lang-change': function(lang) {
        this.init(lang)
        $("#search").trigger('click')

      }
    },
  }
</script>

<style scoped>
  .fck {
    margin-bottom: 20px;
    margin-top: -30px;
  }

  .scroll {
    width: 250%;
  }
</style>
<style>
#pt_table tr td:first-child, #pt_table tr th:first-child, #exp_table tr td:first-child, #exp_table tr th:first-child {
  width: 1%;
  white-space: nowrap;
}

#pt_table td, #pt_table th {
  text-align: left;
  vertical-align: middle}
#epx_table td, #exp_table th {
  text-align: left;
  vertical-align: middle}
</style>
