<template>
    <ClientOnly>
      <Card style="margin-top: 78px; min-height: 200px;"> 
            <template #content>
                <Panel header="Maintainance / Measures" class="bg-white rounded-4 gap-3">
                    <template #icons>
                        
                        <Button class="mr-2" severity="primary" label=" NEW " icon="pi pi-check" @click="openNew()" />
                        <Button class="mr-2" severity="secondary" label=" UPDATE " icon="pi pi-file-edit" @click="onUpdate()" />
                        <Button class="mr-2" severity="danger" label=" DELETE " icon="pi pi-trash" @click="onDelete()" />
                        
                       
                    </template>

                  
                    <div class="g-3 mb-20 needs-validation">
                      <div class="grid nested-grid">
                        <Card class="col-12">
                            <template #content>
                                
                           
                            
                                <DataTable class="p-datatable-sm" :filters="filters" dataKey="id" filterDisplay="row" :value="measures" 
                                    showGridlines stripedRows paginator :rows="10" :rowsPerPageOptions="[5, 10, 20, 50]" 
                                    :globalFilterFields="['kurz']"  
                                    v-model:selection="selectedTyp" selection-mode="single" @row-select="onRowSelect" :meta-key-selection="false"
                                    tableStyle="min-width: 50rem;">
                                    <template #header>
                                      <div class="flex justify-content-end">
                                          <span class="p-input-icon-left">
                                              <i class="pi pi-search" />
                                              <InputText v-model="filters['global'].value" placeholder="Keyword Search" />
                                          </span>
                                      </div>
                                    </template>
                                    <template #empty> No customers found. </template>
                                    <!--<template #loading> Loading customers data. Please wait. </template> -->
                                  <Column v-for="col of columns" :key="col.field" :field="col.field" :header="col.header" sortable :filter-field="col.field" >
                                    
                                  </Column>
                                    
                              </DataTable>
                            </template>
                            
                            <template #footer>

                            </template>
                             
                        </Card>
                      </div>
                    </div>
                    
                </Panel>
            </template>
        </Card>
      </ClientOnly>
      
  </template>
  
  

  <script setup lang="ts">
    //import { MDBBtn, MDBCol, MDBCheckbox, MDBInput, MDBRow, MDBContainer } from "mdb-vue-ui-kit";
    import { ref } from "vue";
    import { FilterMatchMode } from "primevue/api";
    import { useToast } from 'primevue/usetoast';
    import { useDialog } from "primevue/usedialog";
import UpdMeas from "./UpdMeas.vue";

    interface cMeasures {
      id: number;
      kurz: string;
      brust: number;
      laenget: number;
      schulterbreite: number;
      taillenumfangt: number;
      hueftumfang: number;
      innennaht: number;
      laengeb: number;
      taillenumfangb: number;
    }

    
    const kurz = ref("");
    //const loading = ref(true); 
    const selectedTyp = ref("");
    const id = ref(0);
    const toast = useToast();
    const dialog = useDialog();
    const createTypDialog = ref(false);
    const mea = ref({id: 0, kurz: '', brust:0, laenget:0, schulterbreite:0, taillenumfangt:0, hueftumfang:0, innennaht:0, laengeb:0, taillenumfangb:0});
    
    const {data: measures } = await useFetch('http://ubodroid-2:8081/api/v1/meas');
  
    const columns = [
      { field: 'id', header: '#'}, 
      { header: 'Description', field: 'kurz'},
      { header: 'Breast', field: 'brust'},
      { header: 'Lengh Top', field: 'laenget'},
      { header: 'Shoulder Width', field: 'schulterbreite'},
      { header: 'Waist Girth Top', field: 'taillenumfangt'},
      { header: 'Hip Girth', field: 'hueftumfang'},
      { header: 'Inner Seam', field: 'innennaht'},
      { header: 'Length Bottom', field: 'laengeb'},
      { header: 'Waist Girth Bottom', field: 'taillenumfangb'},
    ];

    const filters = ref({
      global: { value: null, matchMode: FilterMatchMode.CONTAINS },
      kurz: {value: null, matchMode: FilterMatchMode.STARTS_WITH }
    })

    const onRowSelect = (event) => {
      id.value = event.data.id;
      kurz.value = event.data.kurz;
      mea.value = event.data;
      console.log('mea nach Auswahl: ',mea);
      toast.add({ severity: 'info', summary: 'Measure Selected', detail: 'Description: ' + event.data.kurz, life: 3000 });
    };

    const openNew = () => {
        let refmea = ref();
        mea.value = ref({id: 0, kurz: '', brust:'', laenget:'', schulterbreite:'', taillenumfangt:'', hueftumfang:'', innennaht:'', laengeb:'', taillenumfangb:''});
        dialog.open(UpdMeas, { data: {mea}, onClose(options) {
        refmea = options?.data;
        console.log('RefMea = ', refmea);
        if (refmea) {
            doInsert(refmea);
        }
        },});
    
    };

    const hideDialog = () => {
    createTypDialog.value = false;
    };
    
    async function doInsert(t: cMeasures) {
      let fd = new FormData();
      fd.append('kurz', t.kurz);
      fd.append('brust', t.brust.toString());
      fd.append('laenget', t.laenget.toString());
      fd.append('schulterbreite', t.schulterbreite.toString());
      fd.append('taillenumfangt', t.taillenumfangt.toString());
      fd.append('hueftumfang', t.hueftumfang.toString());
      fd.append('innennaht', t.innennaht.toString());
      fd.append('laengeb', t.laengeb.toString());
      fd.append('taillenumfangb', t.taillenumfangb.toString());

      await $fetch('http://ubodroid-2:8081/api/v1/meas',{
      method: 'POST',
      body: fd
      });
      createTypDialog.value = false;
      toast.add({ severity: 'success', summary: 'New Measure created', detail: 'Description: ' + t.kurz, life: 3000 });
      await refreshNuxtData();
    console.log('POST ausgeführt...'+ t.kurz);
    } 

    async function onUpdate() {
        let refmea = ref();
        dialog.open(UpdMeas, { data: {mea}, onClose(options) {
        refmea = options?.data;
        console.log('RefMea = ', refmea);
        if (refmea) {
            doUpdate(refmea);
        }
        },});
     
    } 

    async function doUpdate(t: cMeasures) {
      let fd = new FormData();
      fd.append('id', t.id.toString());
      fd.append('kurz', t.kurz);
      fd.append('brust', t.brust.toString());
      fd.append('laenget', t.laenget.toString());
      fd.append('schulterbreite', t.schulterbreite.toString());
      fd.append('taillenumfangt', t.taillenumfangt.toString());
      fd.append('hueftumfang', t.hueftumfang.toString());
      fd.append('innennaht', t.innennaht.toString());
      fd.append('laengeb', t.laengeb.toString());
      fd.append('taillenumfangb', t.taillenumfangb.toString());

      await $fetch('http://ubodroid-2:8081/api/v1/meas/'+t.id,{
      method: 'PUT',
      body: fd
      });
      createTypDialog.value = false;
      toast.add({ severity: 'success', summary: 'Measure updated', detail: 'Description: ' + t.kurz, life: 3000 });
      await refreshNuxtData();
    console.log('PUT ausgeführt...'+ t.kurz);
    } 
    
    async function onDelete() {
      let fd = new FormData();
      fd.append('id', id.value.toString());

      const res = await $fetch('http://ubodroid-2:8081/api/v1/meas/'+id.value,{
      method: 'DELETE',
      body: fd
      });
      if (res) {
        toast.add({ severity: 'success', summary: 'Measure deleted', detail: 'Description: ' + kurz.value, life: 3000 });
      }
      await refreshNuxtData();
      console.log('DELETE ausgeführt...'+ kurz.value);
    } 
    
    
  </script>