<script setup>
import { ref, reactive, computed } from 'vue';
import { useSession } from 'src/composables/useSession';
import { useState } from 'composables/useState';
import { useArrayData } from 'composables/useArrayData';
import LeftMenu from 'components/LeftMenu.vue';
import FetchData from 'components/FetchData.vue';
import TeleportSlot from 'components/ui/TeleportSlot.vue';

const state = useState();
const arrayData = useArrayData('customers');
const session = useSession();

const token = session.getToken();

const searchBackdrop = ref(false);

const provinces = ref([]);
const workers = ref([]);
const workersCopy = ref([]);
const zones = ref([]);

const searchPanel = ref();
const userParams = reactive({});
const tags = computed(() => {
    const params = [];

    for (const param in userParams) {
        params.push({
            label: param,
            value: userParams[param],
        });
    }

    return params;
});

async function doSearch() {
    // let filter = {};
    // if (search.value != '') {
    //     filter = {
    //         where: {
    //             id: search.value,
    //         },
    //     };
    // }
    const params = userParams;

    await arrayData.apply({ params });
    searchPanel.value.hide();
}

// const searchRows = ref([])
// async function pre(value) {
//     let filter = {};
//     if (value != '') {
//         filter = {
//             where: {
//                 id: value,
//             },
//         };
//     }
//     console.log(filter)
//     const rows = await arrayData.request({ userFilter: filter });
//     searchRows.value = rows
// }

function searchParams(params) {
    switch (params) {
        
    }
}

function setWorkers(data) {
    workers.value = data;
    workersCopy.value = data;
}
</script>

<template>
    <fetch-data url="Provinces" @on-fetch="(data) => (provinces = data)" auto-load />
    <fetch-data url="Zones" @on-fetch="(data) => (zones = data)" auto-load />
    <fetch-data
        url="Workers/activeWithInheritedRole"
        :filter="{ where: { role: 'salesPerson' } }"
        @on-fetch="setWorkers"
        auto-load
    />
    <teleport-slot to="#searchbar">
        <q-form @submit="doSearch">
            <q-input id="searchbar" v-model="userParams.search" label="Search" dark dense standout autofocus>
                <template #prepend>
                    <q-icon name="search" />
                </template>
                <template #append>
                    <q-btn @click="searchBackdrop = !searchBackdrop" icon="filter_alt" flat dense>
                        <q-tooltip>Apply search filters</q-tooltip>
                        <div class="q-dialog__backdrop fixed-full" v-if="searchBackdrop"></div>
                        <q-popup-proxy
                            ref="searchPanel"
                            v-model="searchBackdrop"
                            target="#searchbar"
                            no-parent-event
                            fit
                        >
                            <q-card class="q-pa-md">
                                <q-form @submit="doSearch" class="q-gutter-y-md">
                                    <div class="row truncate-chip-labels">
                                        <q-chip
                                            v-for="chip of tags"
                                            :key="chip.label"
                                            @remove="log('Icecream')"
                                            icon="label"
                                            color="primary"
                                            size="sm"
                                            removable
                                        >
                                            <strong>{{ chip.label }}: </strong>
                                            <span>"{{ chip.value }}"</span>
                                        </q-chip>
                                    </div>
                                    <div class="row q-gutter-x-md">
                                        <div class="col">
                                            <q-input
                                                v-model="userParams.search"
                                                label="Search"
                                                hint="Search by id or name"
                                                lazy-rules
                                                autofocus
                                            />
                                        </div>
                                    </div>
                                    <div class="row q-gutter-x-md">
                                        <div class="col">
                                            <q-input label="Fiscal ID" v-model="userParams.fi" lazy-rules />
                                        </div>
                                        <div class="col">
                                            <q-input label="Name" v-model="userParams.name" lazy-rules />
                                        </div>
                                        <div class="col">
                                            <q-input label="Social name" v-model="userParams.socialName" lazy-rules />
                                        </div>
                                    </div>

                                    <div class="row q-gutter-x-md">
                                        <div class="col">
                                            <q-select
                                                v-model="userParams.salesPersonFk"
                                                :options="workers"
                                                option-value="id"
                                                option-label="name"
                                                emit-value
                                                label="Salesperson"
                                                map-options
                                                use-input
                                                :input-debounce="0"
                                            >
                                                <template #before>
                                                    <q-avatar color="orange">
                                                        <q-img
                                                            v-if="userParams.salesPersonFk"
                                                            :src="`/api/Images/user/160x160/${userParams.salesPersonFk}/download?access_token=${token}`"
                                                            spinner-color="white"
                                                        />
                                                    </q-avatar>
                                                </template>
                                            </q-select>
                                        </div>
                                    </div>

                                    <div class="row q-gutter-x-md">
                                        <div class="col">
                                            <q-input label="Phone" v-model="userParams.phone" lazy-rules />
                                        </div>
                                        <div class="col">
                                            <q-input label="Email" v-model="userParams.email" lazy-rules />
                                        </div>
                                    </div>

                                    <div class="row q-gutter-x-md">
                                        <div class="col">
                                            <q-select
                                                label="Province"
                                                v-model="userParams.provinceFk"
                                                :options="provinces"
                                                option-value="id"
                                                option-label="name"
                                                emit-value
                                                map-options
                                            />
                                        </div>
                                        <div class="col">
                                            <q-input label="City" v-model="userParams.city" lazy-rules />
                                        </div>
                                    </div>

                                    <div class="row q-gutter-x-md">
                                        <div class="col">
                                            <q-select
                                                label="Zone"
                                                v-model="userParams.zoneFk"
                                                :options="zones"
                                                option-value="id"
                                                option-label="name"
                                                emit-value
                                                map-options
                                            />
                                        </div>
                                        <div class="col">
                                            <q-input label="Postcode" v-model="userParams.postcode" lazy-rules />
                                        </div>
                                    </div>

                                    <!-- <q-input
                                    label="Phone"
                                    hint="The customer phone"
                                    lazy-rules
                                    :rules="[(val) => (val && val.length > 0) || 'Please type something']"
                                /> -->

                                    <div>
                                        <q-btn
                                            label="Search"
                                            type="submit"
                                            color="primary"
                                            class="full-width"
                                            rounded
                                        />
                                    </div>
                                </q-form>
                            </q-card>
                        </q-popup-proxy>
                    </q-btn>
                </template>
            </q-input>
        </q-form>
    </teleport-slot>
    <q-drawer v-model="state.drawer.value" show-if-above :width="256" :breakpoint="500">
        <q-scroll-area class="fit text-grey-8">
            <LeftMenu />
        </q-scroll-area>
    </q-drawer>
    <q-page-container>
        <router-view></router-view>
    </q-page-container>
</template>

<style lang="scss">
#searchbar,
.search-panel {
    width: 400px;
}
</style>
