<style>
.team-img {
  border-radius: 50%;
}
.vertical-alt {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
.limit{
  margin-top: 0.5rem;
  word-break: break-all;
}
</style>
<template>
  <main>
    <modal-window v-model='inviteModal' @click.stop='() => {}'>
      <div slot="header">
        <p>Invite people to {{$route.params.username}}</p>
      </div>
      <div slot='main' class="modal-card-body">
        <b-field label="Amount of uses (0 is Unlimited)">
          <b-input :value="invite.maxUses" v-model="invite.maxUses">
          </b-input>
        </b-field>
        Please select a role for the user to be auto assigned (optional)
        <div class="field">
          <br>
          <b-radio v-model="invite.RoleId"
                   v-for="role in roles"
                   :key="role.id"
                   :value="role.id"
                   :native-value="role.id"
                   type="is-info">
            {{role.name}}
          </b-radio>
        </div>
        <b-button @click="generateInvite()">Refresh</b-button>
        <b-field label="Invite URL">
          <b-input
            :value="'https://kaverti.com/invite/' + invite.code"
            placeholder="Loading"
            disabled="disabled">
          </b-input>
        </b-field>
      </div>
      <button slot='footer' class='button button--modal' @click.stop='setShareModalState(false)'>OK</button>
    </modal-window>
    <div class="section column">
      <div class="box">
        <h1>Invites</h1>
        <b-button class="button field is-danger" @click="invalidate()"
                :disabled="!selected">
          Delete selected
        </b-button>
        &nbsp;
        <b-button class="field is-info" @click="generateInvite()">
          Generate invite
        </b-button>
        <b-table
          :data="users"
          :paginated="isPaginated"
          :per-page="perPage"
          :current-page.sync="currentPage"
          :pagination-simple="isPaginationSimple"
          :pagination-position="paginationPosition"
          :default-sort-direction="defaultSortDirection"
          :pagination-rounded="isPaginationRounded"
          :sort-icon="sortIcon"
          :opened-detailed="defaultOpenedDetails"
          :sort-icon-size="sortIconSize"
          :selected.sync="selected"
          focusable
          default-sort="user.id"
          aria-next-label="Next page"
          aria-previous-label="Previous page"
          aria-page-label="Page"
          aria-current-label="Current page">

          <b-table-column field="user.code" label="Code" sortable v-slot="props">
            {{ props.row.code }}
          </b-table-column>


          <b-table-column field="user.uses" label="Uses" sortable v-slot="props">
            {{ props.row.uses }}
          </b-table-column>

          <b-table-column field="user.maxUses" label="Max Uses" sortable v-slot="props">
            {{ props.row.maxUses }}
          </b-table-column>

          <b-table-column field="user.User.username" label="Created by" sortable v-slot="props">
            {{ props.row.User.username }}
          </b-table-column>

          <b-table-column field="date" label="Date" sortable centered v-slot="props">
                <span class="tag is-success">
                    {{ new Date(props.row.createdAt).toLocaleDateString() }}
                </span>
          </b-table-column>
        </b-table>
      </div>
    </div>
    <p name='fade' mode='out-in'>
    <center><loading-message key='loading' v-if='loading'></loading-message></center>
    <center><div class='overlay_message' v-if='!loading && !users.length'>
      Something went wrong while loading the Transaction Log, check your internet connection, or check the <a href="https://status.troplo.com">Service Status</a>
    </div></center></p>
  </main>
</template>
<script>
import LoadingMessage from '../LoadingMessage';
import ModalWindow from "@/components/ModalWindow";
import throttle from 'lodash.throttle';
import AjaxErrorHandler from '../../assets/js/errorHandler';

export default {
  name: 'Transactions',
  components: {
    LoadingMessage,
    ModalWindow
  },
  data () {
    return {
      search: '',
      users: [],
      roles: [],
      isPaginated: true,
      isPaginationSimple: false,
      isPaginationRounded: false,
      paginationPosition: 'bottom',
      defaultSortDirection: 'asc',
      sortIcon: 'arrow-up',
      sortIconSize: 'is-small',
      currentPage: 1,
      perPage: 15,
      deleteCode: '',
      defaultOpenedDetails: [1],
      showDetailIcon: true,
      selected: null,
      invite: {
        maxUses: 0,
        RoleId: 0,
        code: ''
      },
      loading: true,
      offset: 0,
      limit: 15,
      showTeamTab: 0,
      inviteModal: false,
      tcreateProd: {
        username: '',
        name: '',

        loading: false,

        errors: {
          username: '',
          name: ''
        }
      },

      roleOptions: [
        { name: 'Admins', value: 'admin' },
        { name: 'Users', value: 'user' }
      ],
      roleSelected: ['admin', 'user'],

      tableSort: {
        column: 'username',
        sort: 'desc'
      }
    }
  },
  methods: {
    invalidate() {
      this.axios
        .delete(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/admin/' + this.$route.params.username + '/invites/delete/' + this.selected.code)
        .then(()=> {
          this.resetFetchData()
          this.selected = null
        })
        .catch((e) => {
          AjaxErrorHandler(this.$store)(e)
        })
    },
    generateInvite () {
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/admin/' + this.$route.params.username + '/invites/create', {
          maxUses: this.invite.maxUses,
          RoleId: this.invite.RoleId
        })
        .then(res => {
          this.invite.code = res.data.code
          this.inviteModal = true
        }).catch(e => {
        AjaxErrorHandler(this.$store)(e)
      })
    },
    fetchData () {
      if(this.offset === null) return;

      let url = process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/admin/${this.$route.params.username}/invites/list?
					sort=${this.tableSort.column}
					&order=${this.tableSort.sort}
					&offset=${this.offset}
				`;
      if(this.roleSelected.length === 1) {
        url += '&role=' + this.roleSelected[0];
      }
      if(this.search.length) {
        url += '&search=' + encodeURIComponent(this.search.trim());
      }

      this.loading = true;
      this.axios
        .get(url)
        .then(res => {
          this.users.push(...res.data);
          this.loading = /*loading =*/ false;

          //If returned data is less than the limit
          //then there must be no more pages to paginate
          if(res.data.length < this.limit) {
            this.offset = null;
          } else {
            this.offset+= this.limit;
          }
        })
        .catch(e => {
          AjaxErrorHandler(this.$store)(e);
          this.loading = /*loading =*/ false;
        });
      this.axios
        .get( process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/view/' + this.$route.params.username + "/roles")
        .then(res => {
          this.roles.push(...res.data);
          this.loading = /*loading =*/ false;

          //If returned data is less than the limit
          //then there must be no more pages to paginate
          if(res.data.length < this.limit) {
            this.offset = null;
          } else {
            this.offset+= this.limit;
          }
        })
        .catch(e => {
          AjaxErrorHandler(this.$store)(e);
          this.loading = /*loading =*/ false;
        });
    },
    resetFetchData () {
      this.offset = 0;
      this.users = [];
      this.roles = [];

      this.fetchData();
    }
  },
  getNewerUsers () {
    this.loadingNewer = true

    this.axios
      .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'transactions' + '?limit=' + this.newUsers)
      .then(res => {
        this.loadingNewer = false
        this.newUsers = 0

        this.threads.unshift(...res.data.Threads)
      })
      .catch((e) => {
        this.loadingNewer = false
        AjaxErrorHandler(this.$store)(e)
      })
  },
  mounted () {
    this.fetchData();
  },
  watch: {
    tableSort: 'resetFetchData',
    roleSelected: 'resetFetchData',
    search: throttle(function () {
      this.resetFetchData();
    }, 200)
  }
}
</script>
