<template>
<div class="container-fluid">
<section class="content">
    <div class="header pb-2">
      
          <div class="header-body">
            <div class="row align-items-center py-4">
              <div class="col-lg-6 col-md-7">
                <nav
                  aria-label="breadcrumb"
                  class="d-none d-md-inline-block ml-md-4"
                >
                  <ol class="breadcrumb breadcrumb-links">
                    <li class="breadcrumb-item">
                      <a href="#"><i class="fas fa-home"></i></a>
                    </li>
                    <li class="breadcrumb-item">
                      <a href="#">Dashboards</a>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page">
                      ລາຍການຜູ້ໃຊ້
                    </li>
                  </ol>
                </nav>
              </div>
              <div class="col-lg-6 col-md-5 text-right">
                  <router-link  v-if="$store.getters['getroles'].includes('user_add')" to="/users/add" class="btn btn-sm btn-primary btn-round btn-icon"> <span class="btn-inner--icon"><i class="fas fa-plus"></i ></span> <span class="btn-inner--text">ເພີ່ມຜູ້ໃຊ້</span> </router-link >
                    
              </div>
            </div>
          </div>
        
      </div>
    <div class="row" v-if="isLoggedIn">
        <div class="col-12">
            <div class="card">
                <!-- Card header -->
                <div class="card-header border-0">
                    <div class="row">
                        <div class="col-6">
                            <h3 class="mb-0">ລາຍການຜູ້ໃຊ້</h3>
                        </div>
                        <div class="col-6 text-right">
                            <div class="form-group " style=" margin-bottom:0;">
                                        <div class="input-group input-group-merge">
                                        <input class="form-control" type="text" placeholder="ຄົ້ນຫາຂໍ້ມູນ..." v-model="search" v-on:keyup="this.searchUser($event)">
                                        <div class="input-group-append">
                                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        </div>
                                        </div>
                                    </div>
                        </div>

                    </div>


                </div>
               
                                    
                   
                <!-- Light table -->
                <div class="table-responsive">
                    <table class="table align-items-center table-flush">
                        <thead class="thead-light">
                            <tr>
                                <th>ID</th>
                                <th>ຊື່ຜູ້ໃຊ້</th>
                                <th>ຕິດຕໍ່</th>
                                <th>ສະຖານະ</th>
                                <th v-if="$store.getters['getroles'].includes('user_edit') || $store.getters['getroles'].includes('user_remove')">ຈັດການ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-if="loading">
                                <td colspan="5" class="text-center">
                                <content-loader viewBox="-10 10 450 110" >
                                        <rect x="0" y="0" rx="3" ry="3" width="350" height="5" />
                                        <rect x="10" y="20" rx="3" ry="3" width="320" height="5" />
                                        <rect x="0" y="40" rx="3" ry="3" width="370" height="5" />
                                        <rect x="10" y="60" rx="3" ry="3" width="350" height="5" />
                                        <rect x="0" y="80" rx="3" ry="3" width="300" height="5" />
                                        <rect x="10" y="100" rx="3" ry="3" width="380" height="5" />
                                </content-loader>
                                </td>
                            </tr>
                            <tr v-for="user in users.data" :key="user.id">
                                <th>{{ user.id }}</th>
                                <td class="table-user">
                                    <img v-bind:src="'images/avatars/'+user.images"
                                        class="avatar rounded-circle mr-3"
                                     v-if="user.images"/>
                                     <img v-bind:src="'images/add_img_bt.png'"
                                        class="avatar rounded-circle mr-3"
                                     v-if="!user.images"/>
                                    <b>{{ user.name }} {{ user.last_name }}</b>
                                </td>
                                <td>
                                    <span class="text-muted"
                                        >ເບີໂທ: {{user.tel}} <br />
                                        ອີເມວລ໌: {{user.email}}</span
                                    >
                                </td>
                                <td>
                                    <span class="text-muted"
                                        >ສະຖານະ: {{user.status}} <br />
                                        ປະເພດຜູ້ໃຊ້: {{user.user_type}}</span
                                    >
                                </td>
                                <td class="table-actions" v-if="$store.getters['getroles'].includes('user_edit') || $store.getters['getroles'].includes('user_remove')">
                                    <div class="col-auto">
                                    <button type="button" class="btn btn-sm btn-neutral mr-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="fas fa-ellipsis-h"></i>
                  </button>
                  <div class="dropdown-menu dropdown-menu-right" style="">
                      <router-link v-if="$store.getters['getroles'].includes('user_edit')" :to="{name: 'editusers', params: { id: user.id }}" class="dropdown-item"> <i class="fas fa-user-edit text-info"></i>ແກ້ໄຂຂໍ້ມູນ</router-link>
                    <a v-if="$store.getters['getroles'].includes('user_remove')" class="dropdown-item" href="javascript:void(0)" @click="deleteUser(user.id)"><i class="fas fa-trash text-red"></i>ລຶບຂໍ້ມູນ</a>
                  </div></div>
                                </td>
                            </tr>
                        </tbody>
                    </table>

                  <vuePagination
                  :pagination="users"
                  @paginate="getUsers()"
                  :offset="4"
                  ></vuePagination>

                </div>
            </div>

            <!-- /.card -->
        </div>
    </div>
   </section>
</div>
</template>

<script>

export default {
    data() {
        return {
            editmode: false,
            users: [],
            current: 1,
            pageSize: 4,
            search:'',
            loading:false,
            isLoggedIn: false,
        };
    },
    comments: {
        // VueJsDatatable
    },
    methods: {
        getUsers(bpage) {
            this.loading = true
            this.$Progress.start();
            if(typeof bpage == 'undefined'){
                this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                axios.get(`/api/users?page=${this.users.current_page}&s=${this.search}`)
                    .then((response) => {
                        this.loading = false
                        if(response.data.message){
                            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+ response.data.message }, 4000)
                            this.$Progress.fail()
                        } else {
                                if(response.data.data.length < 1){
                                const bp = this.users.current_page-1;
                                if(bp >= 1){ this.getUsers(bp) }else{ this.users = response.data;
                                this.$Progress.finish()}
                            }else{
                                this.users = response.data;
                                this.$Progress.finish()
                            }
                        }
                        
                    })
                    .catch((error) => {
                        this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                        //console.error(error)
                        this.$Progress.fail()
                    })
                })
            }
            else
            {
                this.loading = true
              //  console.log('bpage=='+bpage)
                this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                axios.get(`/api/users?page=${bpage}`)
                    .then((response) => {
                        this.loading = false
                        if(response.data.message){
                            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+ response.data.message }, 4000)
                            this.$Progress.fail()
                        } else {
                             this.users = response.data;
                            this.$Progress.finish()
                        }
                            
                    })
                    .catch((error) => {
                        this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                        this.$Progress.fail()
                    });
                });
            }

        },
        deleteUser(id) {
            this.$swal.fire({
            title: 'ທ່ານແນ່ໃຈບໍ່?',
            text: "ທີ່ຈະລຶບຂໍ້ມູນນີ້!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'ລຶບເລີຍ!',
            cancelButtonText: 'ຍົກເລີກ'
            }).then((result) => {
            if (result.isConfirmed) {

                this.$Progress.start()
                this.$axios.get('/sanctum/csrf-cookie').then(response => {
                    this.$axios.delete(`/api/users/delete/${id}`)
                        .then(response => {
                            if(response.data.message){
                                this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+ response.data.message }, 4000)
                                this.$Progress.fail()
                            } else {
                                this.getUsers()
                            this.$notify({ group: "sucess", title: "ສຳເລັດ!", text: " ຂໍ້ມູນໄດ້ຖຶກລຶບອອກແລ້ວ! " }, 2000)
                            this.$Progress.finish()
                            }
                        })
                        .catch((error)=> {
                            this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+error.message }, 4000)
                          //  console.error(error)
                            this.$Progress.fail()
                        });
                })
            }
            })
        },
        searchUser(e){
           if(!this.search){
                this.doSearch()
           }
         if (e.which === 13) {
            this.doSearch()
            }

        },
        doSearch(){
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
                axios.get(`/api/users?page=1&s=${this.search}`)
                    .then((response) => {
                            this.users = response.data;
                            this.$Progress.finish()
                    })
                    .catch(() => {
                        console.error(error)
                        this.$Progress.fail()
                    })
                })
        }
    },
    mounted() {
       // console.log("User Component mounted.");
    },
    created() {

        this.$axios.get(`/api/users/checkauth`).then((response) => {
            if (!response.data.isLogin) {
                window.location.href = "/";
            }
            })

            this.$Progress.start()
            this.getUsers()
            this.$Progress.finish()
        this.$axios.get(`/api/users/checkauth`).then((response) => { if (!response.data.isLogin) { window.location.href = "/"; } });
    
    if(window.Laravel.isLoggedin){
           this.isLoggedIn = true
        }

    },
    beforeRouteEnter(to, from, next) {
        if (!window.Laravel.isLoggedin) {
            window.location.href = "/";
        }
        next();
    }
};
</script>
