<script setup>
import GuestLayout from '@/Layouts/GuestLayout.vue';
import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import SecondaryButton from '@/Components/SecondaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import Multiselect from '@/Components/MultiSelect.vue';
import { Head, Link, useForm } from '@inertiajs/inertia-vue3';
import rpoFields from '../Data/MultiSelectOptionsRPO';
import ConditionDisplay from '@/Components/ConditionStatement.vue';
import QueryBuilder from '@phongthien/vue3-query-builder';
import Input from '@/Components/Input.vue';
import Number from '@/Components/Number.vue';
import JsonQueryBuilder from '@/Components/JsonQueryBuilder.vue';
import { onMounted, ref, computed } from 'vue';
import { defineEmits } from 'vue'
import { Inertia } from '@inertiajs/inertia';
import rpoJsonData from '../Data/RpoTree.json';

const query = ref({
        condition: 'and',
        rules: [{
          id: 'addresses.street',
          operator: '=',
          value: 'V. Clementisa'
          }, {
          condition: 'and',
          rules: [{
            id: 'fullNames.value',
            operator: '(',
            value: 'Cobra s.r.o.'
          }, {
            id: 'equities.valuePaid',
            operator: '<=',
            value: 80000
          }]
        }]
      })
    

const submit = () => {
    console.log('Post data');
    console.log(query.value);
    Inertia.post(`/search`, query.value);
};

function createRPOmulti(tree,flatListRpo, level = 0, fullPathRpo = []) {
    console.log('keys=',Object.keys(tree));
    console.log('TT=',typeof tree);
    let fullPath = [ ...fullPathRpo ] ;      
    if (tree.desc != undefined) fullPath.push(tree.desc);
    
    if (level == 0 || tree.type == "Object" || tree.type == "Array" || tree.type == undefined) {
      Object.keys(tree).forEach(k => {
        console.log('k=',k);
        console.log('obj=',tree[k]);
        console.log(typeof tree[k]);
        console.log('t=',tree[k].type);
        console.log('rec=',k);
        if (typeof tree[k] != 'string') {
          console.log('DESC=',tree[k].desc);
          createRPOmulti(tree[k], flatListRpo, level + 1, fullPath );
        }
      });
  } else {
          flatListRpo.push({"name":tree.name, "type": tree.type, "desc": fullPath.join(' => ') });
  }
}

const rpoMultiselect = computed(() => {
    console.log('Rpo Multiselect');
    var flatList = [];
    createRPOmulti(rpoJsonData, flatList);
    return flatList;
});


</script>

<template>
    <GuestLayout>
        
        <Head title="Register" />

        <JsonQueryBuilder :query="query" :queryOptions="rpoMultiselect" @run-query="submit" ></JsonQueryBuilder>

    </GuestLayout>
</template>
