<template>
  <v-expansion-panels>

    <v-row class="px-10 py-5" align="center">
      <v-text-field
        v-model="searchKey"
        append-outer-icon="mdi-magnify"
        class="pt-5"
        placeholder="Введите чтобы начать поиск"
        @click:append-outer="searchTrigger"
        @keyup.enter="searchTrigger"
      />
    </v-row>

    <v-expansion-panels class="admin-users" v-if="users">
      <v-expansion-panel v-for="user in users.users" :key="user.user_id">
        <v-expansion-panel-header @click="() => {}">
          <v-col cols="6">
            <div class="user-contacts">
              <span>                                                
                <b>{{ user.first_name }}</b>
              </span>
              <span>
                {{ user.email }}
              </span>
            </div>
          </v-col>
          <v-col cols="6">
            <span> </span>
            <span> </span>
            <v-divider vertical></v-divider>
            <div class="user-info">
              <span>бан: {{ user.ban_status ? "да" : "нет" }}</span>
              <span>мут: {{ user.mut_status ? "да" : "нет" }}</span>
              <span>права: {{ user.user_permission_group_display_name }}</span>
            </div>
          </v-col>
          <v-col cols="2">
            <v-btn link tile color="success" @click="openEditor(user)">
              <v-icon center> mdi-pencil </v-icon>
            </v-btn>
            <v-btn tile color="error" @click="deleteUser(user)">
              <v-icon center> mdi-delete-outline </v-icon>
            </v-btn>
          </v-col>
        </v-expansion-panel-header>
      </v-expansion-panel>
    </v-expansion-panels>

    <v-pagination
      v-model="counter"
      :length="users ? users.total_pages : 0"
      ref="pagination"
      v-if="users.total_users"
      @input="onPageChanged"
      :next-icon="'Вперед'"
      :prev-icon="'Назад'"
      :next-aria-label="'next-text'"
      :prev-aria-label="'prev-text'"
      :page-aria-label="'page-text'"
      :current-page-aria-label="'current-page'"
      total-visible="10"
      color="gray"
      class="mt-5"
    ></v-pagination>

    <modal height="auto" name="user-editor" class="user-editor__modal">
      <h2>Редактирование данных</h2>
      <v-text-field
        :value="editingUser.first_name"
        v-model="editingUser.first_name"
        label="Никнейм"
        >Никнейм</v-text-field
      >
      <v-text-field
        label="Емейл"
        :value="editingUser.email"
        v-model="editingUser.email"
        >Емейл</v-text-field
      >
      <v-text-field
        label="Телефон"
        :value="editingUser.phone"
        v-model="editingUser.phone"
        >Телефон</v-text-field
      >
      <v-select
        class="user-editor__select"
        :items="permissionGroups"
        item-text="name"
        item-value="code"
        v-model="editingUser.user_permission_group"
        label="Права"
      ></v-select>

      <v-switch v-model="editingUser.mut_status" color="orange" inset label="Мут"></v-switch>
      <v-switch v-model="editingUser.ban_status" color="red" inset label="Бан"></v-switch>

      <v-btn
        class="user-editor__modal-button mr-4"
        color="primary"
        @click="editUser"
        >Сохранить</v-btn
      >
      <v-btn
        class="user-editor__modal-button"
        color="error"
        @click="$modal.hide('user-editor')"
        >Отмена</v-btn
      >
    </modal>
  </v-expansion-panels>
</template>

<script>
export default {
  layout: "admin",
  data() {
    return {
      users: false,
      counter: 1,
      editingUser: false,
      searchKey: '',
      permissionGroups: [
        {
          code: 0,
          name: "Гость",
        },
        {
          code: 1,
          name: "Пользователь",
        },
        {
          code: 2,
          name: "Менеджер по рекламе",
        },
        {
          code: 3,
          name: "Репортер",
        },
        {
          code: 4,
          name: "Модератор",
        },
        {
          code: 5,
          name: "Администратор",
        },
      ],
    };
  },

  async mounted() {
    await this.loadUsers();
  },

  methods: {
    async onPageChanged() {
      window.scrollTo({ top: 0, behavior: "smooth" });
      await this.loadUsers();
    },
    
    async editUser() {
      const result = await this.$swal.fire({
        title: "Вы уверены, что хотите отредактировать пользователя?",
        showCancelButton: true,
        confirmButtonText: "Принять",
        icon: "question",
        cancelButtonText: `Отменить`,
        confirmButtonColor: `#1976d2`,
        denyButtonColor: `#2196f3`,
      });

      if (result.isDenied) {
        this.$swal.fire("Отмена редактирования", "", "info");
        return;
      } 
      
      else if (result.isConfirmed) {

        await this.$axios.post("/authorized/admin/user/profile/update", {
          target_id: this.editingUser.user_id,
          first_name: this.editingUser.first_name,
          email: this.editingUser.email,
          phone:
            this.editingUser.phone.length >= 3
              ? this.editingUser.phone
              : "без номера",
        });

        await this.$axios.post("/authorized/admin/user/permission_group/update", {
          user_permission_group_id: this.editingUser.user_permission_group,
          user_id: this.editingUser.user_id,
        });

        await this.$axios.post("/authorized/admin/user/profile/ban_or_mute", {
          target_id: this.editingUser.user_id,
          ban_status: this.editingUser.ban_status,
          mut_status: this.editingUser.mut_status,
        });

        await this.loadUsers();
        this.$swal.fire("Готово!", "", "success");
        this.$modal.hide("user-editor");
      }
    },

    getPermission(num) {
      return this.permissionGroups.find((el) => el.code == num);
    },

    openEditor(user) {
      this.editingUser = Object.assign({}, user);
      this.$modal.show("user-editor");
    },

    async deleteUser(user) {
      const result = await this.$swal.fire({
        title: "Вы уверены, что хотите удалить пользователя?",
        showCancelButton: true,
        confirmButtonText: "Удалить",
        icon: "error",
        cancelButtonText: `Не удалять`,
        confirmButtonColor: `#ab003c`,
        denyButtonColor: `#2196f3`,
      });

      if (result.isConfirmed) {
        await this.$axios.get(
          `authorized/admin/user/profile/delete/${user.user_id}`
        );
        await this.loadUsers();
        this.$swal.fire("Удалено!", "", "error");
      } 
      
      else if (result.isDenied) {
        this.$swal.fire("Отмена удаления", "", "info");
      }
    },

    async searchTrigger() {
      this.counter = 1;
      await this.loadUsers();
    },

    async loadUsers() {
      if(this.searchKey) {
        await this.searchUsers();
        return;
      }
      
      this.users = await this.$axios
        .get(`authorized/admin/user/profiles/list/page_${this.counter}`)
        .then((res) => res.data.data);
    },

    async searchUsers() {
      this.users = await this.$axios
        .get(`authorized/admin/user/profiles/search/${this.searchKey}/page_${this.counter}`)
        .then((res) => res.data.data);
    }
  },
};
</script>

<style lang="scss">
.v-expansion-panel--active,
.v-item--active {
  margin: 0 !important;
  // border: none !important;
}
.v-expansion-panel {
  margin: 0 !important;
}
.v-expansion-panel--active:not(:first-child)::after,
.v-expansion-panel--active + .v-expansion-panel::after {
  opacity: 1 !important;
}
.user-info,
.user-contacts {
  display: flex;
  flex-direction: column;
  span {
    margin-bottom: 6px;
  }
}
.admin-users {
  margin: 0 auto;
}
.user-editor {
  &__modal {
    &-button {
      margin-top: 20px;
    }
    h2 {
      margin-bottom: 20px;
    }
    input {
      border: none;
    }
    .vm--modal {
      max-height: 100vh;
      min-height: 450px;
      padding: 30px;
    }
  }
  &__select {
    input {
      border: none;
      background: rgba(0, 0, 0, 0.06);
      z-index: -1;
      display: none;
    }
  }
}
.v-application--is-ltr .v-expansion-panel-header__icon {
  margin-left: auto;
  display: none;
}
</style>
