<template>

<EmployeesSimpleSearch />

<table class="table table-hover mt-3">
    <thead>
        <tr>
            <th 
                v-for="col in columns"
                @click="onSortBy(col)"
            >
                {{col}}
                <i :style="{visibility: colIsSelected(col) ? 'visible' : 'hidden'}" class="bi" :class="iconSort"></i>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="employee in rows" @click="router.push({name: 'Employees/Details', params: {id: employee.id}})">
            <td v-for="col in columns">
                {{ employee[col] }}
            </td>
        </tr>
    </tbody>

</table>

</template>

<script setup lang="ts">

import EmployeesSimpleSearch from '@/components/Employees/EmployeesSimpleSearch.vue';
import { onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useEmployees } from '@/stores/employees'

const store = useEmployees()
const router = useRouter()
const { rows, meta, columns } = storeToRefs(store)

const sort_by = reactive({
    asc: true,
    column: 'id'
})

onMounted(() => {
    store.fetchFromApi()
})

function colIsSelected(col : string) {
    return col === sort_by.column
}

function onSortBy(col : string) {
    if(col !== sort_by.column) sort_by.asc = true
    else sort_by.asc = !sort_by.asc

    sort_by.column = col
    store.sort_by = (sort_by.asc ? 'asc(' : 'desc(') + sort_by.column + ')'
    store.fetchFromApi() 
}

const iconSort = computed(() => {
    return 'bi-sort-' + (sort_by.asc ? 'down' : 'up')+'-alt'
})

</script>

<style scoped>
table {
    /* table-layout: fixed; */
}

table thead tr:first-child th:first-child {
    width: 51px;
}

table th {
    -ms-user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
    -khtml-user-select: none;
    user-select: none;
    cursor: pointer;
    
}

tr {
    cursor: pointer;
}

</style>