<template>
  <!-- eslint-disable max-len -->
  <div class="container">
    <br />
    <br />
    <div class="row">
      <div class="col-md-12 col-lg-8">
        <div class="title-box-d">
          <h1 class="title-d" style="text-align:left; font-size: 250%">Agent Management</h1>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-2 offset-1">
        <button
          @click="routerGoTo('/status/userManagementPage')"
          type="button"
          class="btn btn-b-n"
        >Private Users</button>
      </div>
      <div class="col-md-2 offset-2">
        <button type="button" class="btn btn-b-n">Agents</button>
      </div>
      <div class="col-md-2 offset-2">
        <button
          type="button"
          class="btn btn-b-n"
          data-toggle="modal"
          :data-target="'#myModal' + i"
        >New Agent</button>
        <div :id="'myModal' + i" class="modal fade" role="dialog">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
              </div>
              <Agency name="Agency" :isAddAgent="false" :item="item" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="d-flex justify-content-between">
        <div class="p-2">
          <input v-model="searchItem" class="form-control" placeholder="Search ..." />
        </div>
      </div>
      <div v-if="Delete === true">
        <alert :text="'Private User removed successfully'" :type="'SUCCESS'" />
      </div>
      <br />
      <table class="table table-bordered">
        <thead>
          <tr>
            <td colspan="11">
              <div class="myWell">
                <h4>Agents</h4>
              </div>
            </td>
          </tr>
          <tr>
            <th>
              <b>ID</b>
            </th>
            <th>
              <b>Name</b>
            </th>
            <th>
              <b>Surname</b>
            </th>
            <th>
              <b>Cell Number</b>
            </th>
            <th>
              <b>Telephone Number</b>
            </th>
            <th>
              <b>Email</b>
            </th>
            <th>
              <b>Role</b>
            </th>
            <th>
              <b>Reset Password</b>
            </th>
            <th>
              <b>Modify</b>
            </th>
            <th>
              <b>Remove</b>
            </th>
            <th>
              <b>Soft Delete</b>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, i) in DisplayItems" :key="i">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.surname }}</td>
            <td>{{ item.cellNumber }}</td>
            <td>{{ item.telephone }}</td>
            <td>{{ item.email }}</td>
            <td v-if="item.user">{{ item.user.role }}</td>
            <td v-else></td>
            <td>
              <button type="button" class="btn" style="margin:2px; color: #60CBEB">Reset</button>
            </td>
            <td>
              <button
                type="button"
                class="btn"
                style="margin:2px; color: #60CBEB"
                @click="routerGoTo('/user/updateProfileInfo')"
              >Edit</button>
            </td>
            <td>
              <button
                type="button"
                @click="Delete(item.id)"
                class="btn"
                style="width: 85px; height:40px; color:#60CBEB"
              >Delete</button>
            </td>
            <td>{{ item.isDeleted}}</td>
          </tr>
        </tbody>
      </table>
      <div class="d-flex justify-content-between">
        <div class="p-1">{{ currentPage + ' / ' + PageCount }}</div>
        <div class="p-1">
          <BasePagination
            :currentPage="currentPage"
            :pageCount="PageCount"
            @nextPage="pageChangeHandle('next')"
            @previousPage="pageChangeHandle('previous')"
            @loadPage="pageChangeHandle"
          />
        </div>
      </div>
    </div>
    <br />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import axios from 'axios';
import _ from 'lodash';
import ItemsPerPageList from '../../../assets/staticData/itemsPerPage';
import BasePagination from '../../shared/basePagination.vue';
import Agency from '../../user/registerAgencySection.vue';
import alert from '../../shared/alert.vue';

export default {
  name: 'agentManagementPage',
  components: {
    BasePagination,
    Agency,
    alert,
  },
  props: {
    delete: Boolean,
  },
  data() {
    return {
      sortKey: '',
      reverse: false,
      searchItem: '',
      itemsPerPageList: ItemsPerPageList,
      visibleItemsPerPageCount: 0,
      currentPage: 1,
      item: {},
    };
  },
  methods: {
    ...mapActions('register', ['getAgents', 'deleteAgent']),
    addNewAgent({ commit }) {
      axios
        .post('/api/agent')
        .then(result => commit('saveAgent', result.data))
        .catch(console.error);
    },
    routerGoTo(goTo) {
      this.$router.push(goTo);
    },
    sortBy(sortKey) {
      this.reverse = this.sortKey === sortKey ? !this.reverse : false;
      this.sortKey = sortKey;
    },
    async pageChangeHandle(value) {
      console.log(value);
      switch (value) {
        case 'next':
          this.currentPage += 1;
          break;
        case 'previous':
          this.currentPage -= 1;
          break;
        default:
          this.currentPage = value;
      }
    },
    onChangeItemsPerPage() {
      if (this.currentPage !== 1) {
        this.currentPage = 1;
      }
    },
    Delete(id) {
      this.deleteAgent(id);
    },
  },
  mounted() {
    this.getAgents();
    try {
      // to assign initial value to itemsPerPage
      if (this.itemsPerPageList && this.itemsPerPageList.length > 0) {
        const [startItem] = this.itemsPerPageList;
        this.visibleItemsPerPageCount = startItem;
      }
    } catch (error) {
      throw error;
    }
  },
  computed: {
    ...mapState('register', ['agents', 'removeAgent']),

    SortDirection() {
      return this.reverse ? 'desc' : 'asc';
    },
    PageCount() {
      return this.visibleItemsPerPageCount !== 0
        ? Math.ceil(this.FilteredItems.length / this.visibleItemsPerPageCount)
        : 1;
    },
    FilteredItems() {
      const list = _.filter(this.agents, item => Object.values(item).some(
          i => JSON.stringify(i)
              .toLowerCase()
              .indexOf(this.searchItem) > -1,
        ),);
      return _.orderBy(list, this.sortKey, this.SortDirection);
    },
    DisplayItems() {
      const list = this.FilteredItems;
      const startSlice = (this.currentPage - 1) * this.visibleItemsPerPageCount;
      let endSlice = this.currentPage * this.visibleItemsPerPageCount;
      if (endSlice > list.length) {
        endSlice = list.length;
      }
      return list.slice(startSlice, endSlice);
    },
  },
};
</script>


<style>
</style>
