<template>
  <div class="content">
    <div class="container">
      <div class="row">
        <div class="col-md-3" id="profile">
          <div class="thumbnail">
            <img v-bind:src="user.avatar_url" style="height:200px;margin-top:13px;">
            <div class="caption">
              <h3><i class="glyphicon glyphicon-user"></i> <strong>{{ user.username }}</strong></h3>
              <p class="text-muted" style="font-size:20px;">今日首胜: {{ activity.today }}/1 </p>
              <p class="text-muted" v-if="showActivity" style="font-size:20px;">{{ activity.name }}首胜:
                {{ activity.total }}/{{ activity.max }} </p>
            </div>
          </div>
        </div>
        <div class="col-md-9">
          <div class="panel panel-default">
            <div class="panel-heading">
              <h3 class="panel-title">{{ lang.athletic }} </h3>
            </div>
            <div class="table-responsive">
              <table class="table table-striped table-bordered table-hover">
                <tbody>
                <tr>
                  <td>D.P</td>
                  <td>{{ user_info.pt }}</td>
                </tr>
                <tr>
                  <td>{{ lang.athletic_rank }}</td>
                  <td>{{ user_info.arena_rank }}</td>
                </tr>
                <tr>
                  <td>{{ lang.win }}</td>
                  <td>{{ user_info.athletic_win }}</td>
                </tr>
                <tr>
                  <td>{{ lang.lose }}</td>
                  <td>{{ user_info.athletic_lose }}</td>
                </tr>
                <tr>
                  <td>{{ lang.draw }}</td>
                  <td>{{ user_info.athletic_draw }}</td>
                </tr>
                <tr>
                  <td>{{ lang.all }}</td>
                  <td>{{ user_info.athletic_all }}</td>
                </tr>
                <tr>
                  <td>{{ lang.ratio }}</td>
                  <td>{{ user_info.athletic_wl_ratio }}%</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="panel panel-default">
            <div class="panel-heading">
              <h3 class="panel-title">{{ lang.entertain }} </h3>
            </div>
            <div class="table-responsive">
              <table class="table table-striped table-bordered table-hover">
                <tbody>
                <tr>
                  <td>EXP</td>
                  <td>{{ user_info.exp }}</td>
                </tr>
                <tr>
                  <td>{{ lang.exp_rank }}</td>
                  <td>{{ user_info.exp_rank }}</td>
                </tr>
                <tr>
                  <td>{{ lang.win }}</td>
                  <td>{{ user_info.entertain_win }}</td>
                </tr>
                <tr>
                  <td>{{ lang.lose }}</td>
                  <td>{{ user_info.entertain_lose }}</td>
                </tr>
                <tr>
                  <td>{{ lang.draw }}</td>
                  <td>{{ user_info.entertain_draw }}</td>
                </tr>
                <tr>
                  <td>{{ lang.all }}</td>
                  <td>{{ user_info.entertain_all }}</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>

          <div class="panel panel-default">
            <div class="panel-heading">
              <h3 class="panel-title">{{ lang.monthlyHistory }} </h3>
            </div>
            <!--<div class="panel-body">-->
            <!--<div style="width:100%;overflow-x:auto;overflow-y:hidden;">
                <table id="rank" class="table table-striped table-bordered table-hover example" ></table>
              </div>-->
            <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
              <table id="monthly_rank" class="table table-striped table-bordered table-hover example"
                     :class="{ scroll: isMobile }"></table>
            </div>
          </div>

          <div class="alert alert-info alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            {{ lang.tagInfo }}
          </div>


          <div class="panel panel-default">
            <div class="panel-heading">
              <h3 class="panel-title">{{ lang.athleticDueHistory }} </h3>
            </div>
            <!--<div class="panel-body">-->
            <!--<div style="width:100%;overflow-x:auto;overflow-y:hidden;">
								<table id="rank" class="table table-striped table-bordered table-hover example" ></table>
							</div>-->
            <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
              <table id="athletic_rank" class="table table-striped table-bordered table-hover example"
                     :class="{ scroll: isMobile }"></table>
            </div>
            <!--</div>-->
            <!--<div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
							<table id="rank" class="table table-striped table-bordered table-hover example" :class="{ scroll: isMobile }" ></table>
					</div>-->
          </div>

          <div class="panel panel-default">
            <div class="panel-heading">
              <h3 class="panel-title">{{ lang.entertainDueHistory }} </h3>
            </div>
            <!--<div class="panel-body">-->
            <!--<div style="width:100%;overflow-x:auto;overflow-y:hidden;">
								<table id="rank" class="table table-striped table-bordered table-hover example" ></table>
							</div>-->
            <div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
              <table id="entertain_rank" class="table table-striped table-bordered table-hover example"
                     :class="{ scroll: isMobile }"></table>
            </div>
            <!--</div>-->
            <!--<div class="table-responsive" style="width:100%;overflow-x:auto;overflow-y:hidden;">
							<table id="rank" class="table table-striped table-bordered table-hover example" :class="{ scroll: isMobile }" ></table>
					</div>-->

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

<script>
import querystring from 'querystring';
import API from '../api'
import {mapGetters} from 'vuex'
import moment from 'moment'
import tb_language from './tb_lang.js'
import Vue from 'vue';


var rankTable;
var rankTable2;
var rankTable3;


export default {
  data() {
    return {
      isMobile: false,
      activity: {
        today: 0,
        name: '新年充电活动',
        max: '15'
      },
      showActivity: false,
      user_info: {
        exp: 0,
        pt: 500,
        entertain_win: 0,
        entertain_lose: 0,
        entertain_draw: 0,
        entertain_all: 0,
        entertain_wl_ratio: 0,
        exp_rank: 0,
        athletic_win: 0,
        athletic_lose: 0,
        athletic_draw: 0,
        athletic_all: 0,
        athletic_wl_ratio: 0,
        arena_rank: 0
      },
      // vsDealerStats: { //发牌姬战绩
      //   win: 0,
      //   lose: 0,
      //   total: 0
      // },
      // vsGenesisStats: { //VS深渊代码战绩
      //   win: 0,
      //   lose: 0,
      //   total: 0
      // },
      vsDuelMonsterStats: { //二期 卡片精灵战绩
        win: 0,
        lose: 0,
        total: 0
      },
      vsMalissStats: { //二期 素体战绩
        win: 0,
        lose: 0,
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters({
      lang: 'getLang',
      user: 'getUser'
    }),
  },


  mounted: function () {
    var _this = this
    $("#search").click(function () {
      _this.renderPage();
    })
    // this.init()
    // window.onhashchange = this.init;
    this.renderPage();
  },


  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) {
      this.isMobile = false;
    } else {
      this.isMobile = true;
    }

    let opt = {
      'username': this.user.username
    }

    // 获取VS发牌姬活动战绩
    // this.fetchVsDealerStats().then(vsDealerStats => {
    // this.vsDealerStats = vsDealerStats;
    // });

    // this.fetchVsGenesisStats().then(vsGenesisStats => {
    // this.vsGenesisStats = vsGenesisStats;
    // });

    this.fetchVsDuelMonsterStats().then(vsDuelMonsterStats => {
    this.vsDuelMonsterStats = vsDuelMonsterStats;
    });

    this.fetchVsMalissStats().then(vsMalissStats => {
    this.vsMalissStats = vsMalissStats;
    });

    API.getUserInfo(opt).then((res) => {
      this.user_info = res.data
      // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Profile.vue---------------------%c:219', 'background:#ed162b', 'background:#7d382d',
      //   res)
    });

  },

  methods: {

    // VS发牌姬成绩
    // async fetchVsDealerStats() {
    //   try {
    //     const apiUrl = 'https://sapi.moecube.com:444/dealer/api/user';
    //     const url = `${apiUrl}/${this.user.username}`;
    //     console.log('发牌姬API', url);
    //     const response = await Vue.http.get(url);
    //     const jsonData = await response.json(); 
    //     console.log('发牌姬response', jsonData.data);
    //     return jsonData.data;
    //   } catch (error) {
    //     console.error('Error fetching user stats:', error);
    //     throw error;
    //   }
    // },

    // // VS深渊代码成绩
    // async fetchVsGenesisStats() {
    //   try {
    //     const apiUrl = 'https://sapi.moecube.com:444/dealer2/api/user';
    //     const url = `${apiUrl}/${this.user.username}`;
    //     console.log('深渊代码API', url);
    //     const response = await Vue.http.get(url);
    //     const jsonData = await response.json(); 
    //     console.log('深渊代码response', jsonData.data);
    //     return jsonData.data;
    //   } catch (error) {
    //     console.error('Error fetching user stats:', error);
    //     throw error;
    //   }
    // },

        // VS卡片精灵成绩
      async fetchVsDuelMonsterStats() {
        try {
          const apiUrl = 'https://sapi.moecube.com:444/dealer3/api/user';
          const url = `${apiUrl}/${this.user.username}`;
          console.log('世界BOSS卡片精灵API: ', url);
          const response = await Vue.http.get(url);
          const jsonData = await response.json(); 
          console.log('世界BOSS卡片精灵response: ', jsonData.data);
          return jsonData.data;
        } catch (error) {
          console.error('Error fetching user stats:', error);
          throw error;
        }
    },

    // VS素体成绩
    async fetchVsMalissStats() {
      try {
        const apiUrl = 'https://sapi.moecube.com:444/dealer4/api/user';
        const url = `${apiUrl}/${this.user.username}`;
        console.log('世界BOSS素体API: ', url);
        const response = await Vue.http.get(url);
        const jsonData = await response.json(); 
        console.log('世界BOSS素体response: ', jsonData.data);
        return jsonData.data;
      } catch (error) {
        console.error('Error fetching user stats:', error);
        throw error;
      }
    },


    exchangeUserInfo(info) {
      let userName = this.user.username
      let exchangeInfo = info
      if (info.usernamea != userName) {
        exchangeInfo = {
          "type": info.type,
          "start_time": info.start_time,
          "isfirstwin": info.isfirstwin,
          "end_time": info.end_time,
          "usernamea": info.usernameb,
          "usernameb": info.usernamea,
          "userscorea": info.userscoreb,
          "userscoreb": info.userscorea,
          "expa": info.expb,
          "expb": info.expa,
          "expa_ex": info.expb_ex,
          "expb_ex": info.expa_ex,
          "pta": info.ptb,
          "ptb": info.pta,
          "pta_ex": info.ptb_ex,
          "ptb_ex": info.pta_ex,
          "winner": info.winner,
        }
      }
      // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Profile.vue---------------------%c:227', 'background:#1b5fbd', 'background:#ce8e6b',
      //   exchangeInfo)
      return exchangeInfo
    },

    exchangeUserInfo3(info) {
      let userName = this.user.username
      let exchangeInfo = info
      if (info.usernamea !== userName) {
        exchangeInfo = {
          "username":info.username,
          "season": info.season,
          "rank": info.rank,
          "pt": info.pt,
          "note": info.note,
          "entertainmentWin": info.entertainmentWin,
          "entertainmentLose": info.entertainmentLose,
          "entertainmentDraw": info.entertainmentDraw,
          "correction": info.correction,
          "athleticWin": info.athleticWin,
          "athleticLose": info.athleticLose,
          "athleticDraw": info.athleticDraw,
        }
      }
      // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Profile.vue---------------------%c:227', 'background:#1b5fbd', 'background:#ce8e6b',
      //   exchangeInfo)
      return exchangeInfo
    },

    init: function () {
    },

    renderPage: function () {
      if (rankTable) {
        rankTable.destroy();
      }

      if (rankTable2) {
        rankTable2.destroy();
      }

      if (rankTable3) {
        rankTable3.destroy();
      }

      var username = this.user.username
      var type = 1;

      rankTable = this.renderRankTable("#athletic_rank", [], "DP");
      rankTable2 = this.renderRankTable("#entertain_rank", [], "");
      rankTable3 = this.renderRankTable3("#monthly_rank", [], "");

      if (!username) return;

      API.getUserDueHistory({username: username, type: "1", page_num: 100}).then((res) => {

        if (rankTable) {
          rankTable.destroy();
        }
        rankTable = this.renderRankTable("#athletic_rank", res.data.data, "DP")

      }, (res) => {

      });

      API.getUserDueHistory({username: username, type: "2", page_num: 100}).then((res) => {
        if (rankTable2) {
          rankTable2.destroy();
        }
        rankTable2 = this.renderRankTable("#entertain_rank", res.data.data, "")
      }, (res) => {
        // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Profile.vue---------------------%c:258', 'background:#ef98b5', 'background:#53116e',
        //   res)
      });

// 获取用户每个月的战斗历史数据
      var monthly = [];
      function fetchData(username, monthOffset) {
        var date = moment().subtract(monthOffset, 'months').format('YYYY-MM');
        let opt = {
          'username': username,
          'season': date,
        };
        return API.getMonthlyHistory(opt)
          .then(response => {
            const res = response.data;
            // console.log(res);
            // 判断是否有返回数据
            if (res) {
              // 继续请求前一个月的数据
              monthly.push(res);
              return fetchData(username, monthOffset + 1);
            } else {
              // 当不再返回数据时，结束递归，并返回最终的 monthly 数组
              return monthly;
            }
          });
      }
      fetchData(username, 1).then(res => {
        if (rankTable3) {
          rankTable3.destroy();
        }
        rankTable3 = this.renderRankTable3("#monthly_rank", monthly, "")
      });


      var _this = this;
      API.getFirstWin({username: username}).then((res) => {
        _this.activity = res.data
        if (_this.activity.name && _this.activity.name.trim().length > 0) {
          _this.showActivity = true;
        }
      }, (res) => {
        // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Profile.vue---------------------%c:271', 'background:#c85336', 'background:#a4c933',
        //   res)
      });
    },

    renderRankTable: function (id, tableData, ttype) {
      tableData = tableData || [];
      var lang = localStorage.getItem('lang') || 'cn';
      var rank = 1;
      // console.log('%c ---------------------src' + '\\' + 'components' + '\\' + 'Profile.vue---------------------%c:284', 'background:#c896f3', 'background:#f332b2',
      //   tableData)
      let that = this
      var processData = tableData.map(function (d) {
        d = that.exchangeUserInfo(d)
        return [d.usernamea, d.usernameb, moment(d.start_time).format('YYYY-MM-DD HH:mm'),
          moment(d.end_time).format('YYYY-MM-DD HH:mm'), d.userscorea, d.userscoreb,
          d.pta, d.pta_ex, d.ptb, d.ptb_ex];
      });
      var table = $(id).DataTable({
        paging: true,
        searching: false,
        ordering: false,
        lengthChange: false,
        info: false,
        data: processData,

        columns: [
          {title: tb_language[lang].playerA},
          {title: tb_language[lang].playerB},
          {title: tb_language[lang].startTime},
          {title: tb_language[lang].endTime},

        ],
        "columnDefs": [
          {
            "render": function (data, type, row) {
              var userscorea = row[4];
              var userscoreb = row[5];
              var diff = (parseFloat(row[6]) - parseFloat(row[7])).toFixed(2)
              if (diff > 0) {
                diff = "+" + diff
              }
              var append = diff + ttype
              if (ttype === "") {
                append = ""
              }
              if (userscorea < 0) {
                return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'><span class='label label-danger'>" + data + "</span></a>  " + append;
              }

              if (userscorea > userscoreb) {
                return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'><span class='label label-success'>" + data + "</span></a> " + append;
              }

              return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'><span class='label label-info'>" + data + "</span></a> " + append;
            },
            "targets": 0
          },
          {
            "render": function (data, type, row) {
              var userscorea = row[4];
              var userscoreb = row[5];
              var diff = (parseFloat(row[8]) - parseFloat(row[9])).toFixed(2)
              if (diff > 0) {
                diff = "+" + diff
              }
              var append = diff + ttype
              if (ttype === "") {
                append = ""
              }
              if (userscoreb < 0) {
                return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'><span class='label label-danger'>" + data + "</span></a> " + append;
              }

              if (userscorea < userscoreb) {
                return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'><span class='label label-success'>" + data + "</span></a> " + append;
              }

              return "<a href='#/userinfo?username=" + encodeURIComponent(data) + "'><span class='label label-info'>" + data + "</span></a> " + append;
            },
            "targets": 1
          },
        ],
        "language": lang === 'en' ? tb_language.en : tb_language.cn
      });

      return table;
    },
    renderRankTable3: function (id, tableData) {
      tableData = tableData || [];
      var lang = localStorage.getItem('lang') || 'cn'
      let that = this
      var processData = tableData.map(function (d) {
        console.log(tableData)
        d = that.exchangeUserInfo3(d);
        var pt=Math.round(d.pt);
        var totoal=d.athleticWin+d.athleticLose;
        return [
          moment(d.season).format('YYYY-MM'),
          d.rank,
          pt,
          d.athleticWin,
          d.athleticLose,
          totoal
        ];
      });
      var table = $(id).DataTable({
        paging: true,
        searching: false,
        ordering: false,
        lengthChange: false,
        info: false,
        data: processData,
        "pageLength": 12, // 设置每页显示12行数据
        columns: [
          {title: tb_language[lang].season},
          {title: tb_language[lang].rank},
          {title: tb_language[lang].pt},
          {title: tb_language[lang].athleticWin},
          {title: tb_language[lang].athleticLose},
          {title: tb_language[lang].total},
        ],
        "columnDefs": [
        ],
        "language": lang === 'en' ? tb_language.en : tb_language.cn
      });

      return table;
    },
  },
}

</script>
