<template>
  <b-row>
    <b-col md='12' class="text-right">
      <b-button variant="primary" class="text-light" @click="showModal">
        <font-awesome-icon icon="plus" />
        Novo usuário
      </b-button>
    </b-col>
    <b-col md="12">
      <table class="table table-responsive table-custom">
        <thead>
        <tr class="akkurat-regular text-center">
          <th>Nome</th>
          <th>Email</th>
          <th>Perfil</th>
          <th>Ramal</th>
          <th>Data Criação</th>
          <th>&nbsp;</th>
        </tr>
        </thead>

        <tbody>
        <tr v-for="user in usersList" :key="user.id">
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
          <td>{{printRoles(user)}}</td>
          <td><span v-if="user.ramal != null">{{user.ramal}}</span> <span v-else> - </span></td>
          <td>{{user.created_at | formatDateTimeDDMMAAAA}}</td>
          <td>
            <div class="justify-content-between d-flex">
              <b-button variant="primary" class="text-light mr-2" @click="editUser(user.id)">
                <font-awesome-icon icon="edit" />
              </b-button>
              <b-button variant="primary" class="text-light" @click="remove(user)">
                <font-awesome-icon icon="trash" />
              </b-button>
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <b-spinner v-if="loading" type="grow" label="Spinning"></b-spinner>
      <b-alert v-if="usersList.length == 0 && !loading" variant="primary" show>não há usuários para
        mostrar
      </b-alert>
    </b-col>

    <user-modal @success="searchUsers" />

  </b-row>
</template>

<script>
  import userModal from '@/components/modals/User/UserDetail';
  import serviceUser from '@/services/resources/UserService';

  const service = serviceUser.build();

const defaultRoles = [
        {value: 'ADM', text: "Administrador"}, 
        {value: 'Analyst', text: "Analista"}, 
        {value: 'Marketing', text: "Marketing"}, 
        {value: 'ProcessOrders', text: "Gestor de Pedidos"}, 
        {value: 'Integration', text: "Intagração "},
        {value: 'ManagerComercial', text: "Diretor Comercial"},
        {value: 'SAC', text: "SAC"}
      ] ;

  export default {
    components: {
      userModal
    },
    data() {
      return {
        users: [],
        loading: false
      };
    },
    computed: {

      usersList() {
        return this.users;
      }
    },
    methods: {
      filters() {

        return {
          roles: 'ADM,Analyst,Integration,ProcessOrders,ManagerComercial,SAC',
          with: 'roles'
        }
      },
      searchUsers() {
        var vm = this;
        this.loading = true;

        service
          .search(this.filters())
          .then(resp => {
            this.users = resp;
            vm.loading = false;
          })
          .catch(err => {
            const resp = JSON.parse(err.response.data);
            vm.$fire({
              title: 'Falha na solicitação',
              text: resp.msg,
              type: 'error'
            });

            vm.loading = false;
          });
      },
      printRoles(user) {
        if(user.roles.length > 0){

          return defaultRoles.find( role => user.roles[0].name == role.value).text;

        }

      },
      showModal() {
        this.$modal.show('user-create-edit');
      },
      editUser(userId) {
        this.$modal.show('user-create-edit', { userId });
      },
      remove(user) {
        this
          .$fire({
            title: 'Remover usuário',
            html: `Deseja realmente remover o usuário <strong>${user.name}</strong>?`,
            type: 'question',
            showCancelButton: true,
            confirmButtonText: 'Deletar',
            cancelButtonText: 'Cancelar'
          })
          .then(async ({ value }) => {
            if (value) {
              let text = 'Usuário removido com sucesso.';
              let type = 'success';
              try {
                await service.destroy(user.id);
                this.searchUsers();
              } catch (error) {
                console.error(error);
                text = 'Ocorreu um erro ao tentar remover o usuário';
                type = 'danger';
              } finally {
                this.$fire({
                  title: 'Remoção de usuário',
                  type,
                  text
                });
              }
            }
          });
      }
    },
    mounted() {
      this.searchUsers();
    }
  };
</script>
<style scoped lang="scss">
  @import "@/assets/css/main.scss";
</style>
