<template>
    <v-sheet :height="height" class="pa-1 overflow-y-auto">
        <v-treeview dense selectable open-all ref="CustomersTree"
            :disabled="disabled"
            selection-type="leaf"
            :items="[{id: -1, type: 'customer', name: __('Selectați clienții și utilizatorii'), children: tree}]"
            v-model="selected"
        >
            <template #label="{item}">
                
                <div class="text-caption mb-1">

                    <div class="d-flex align-center justify-space-between" v-if="item.type == 'customer'">

                        <div :class="item.status == 'active' ? 'green--text' : 'red--text'">
                            {{ item.name }}
                        </div>

                        <v-chip v-if="item.id > -1" small outlined :color="item.status == 'active' ? 'green' : 'red'">
                            {{ __(item.status == 'active' ? 'Activ' : 'Inactiv')  }}
                        </v-chip>
                    </div>

                    <template v-else>
                        <div class="d-flex align-center">
                            <user-avatar
                                :user="item"
                            />

                            <v-sheet width="200" class="pl-1 text-truncate">
                                {{item.full_name}}
                            </v-sheet>

                            <v-sheet width="70">
                                <v-chip small outlined :color="item.activated == 1 ? 'green' : 'red'">
                                    {{ __(item.activated == 1 ? 'Activ' : 'Inactiv')  }}
                                </v-chip>
                            </v-sheet>

                            <account-role
                                v-if="item.role.id"
                                :role="item.role"
                                :app="app"
                                :form="null"
                            />

                            <span v-else class="red--text text-caption">
                                {{ __('Nu are rol') }}
                            </span>
  
                        </div>
                    </template>
                </div>
            </template>
        </v-treeview>
    </v-sheet>
</template>

<script>

    export default {
        props: {        
            app: {required: true},
            height: {default: 300},
            value: {required: true},
        },

        data: () => ({
            customers: [],
            accounts: [],
            tree: [],
            selected: [],
            disabled: false,
        }),

        computed: {
            customersDataProvider() {
                return this.app.dataSession.Customers;
            },

            accountsDataProvider() {
                return this.app.dataSession.Accounts;
            },
        },

        watch: {
            selected: function() {
                
                let selected = _.map(this.selected, item => {

                    item = item + '';
                    
                    let parts = item.split('.');
                    
                    return {
                        customer_id: parts[0],
                        user_id: parts.length == 2 ? parts[1] : null,
                    }
                })

                let r = {};

                _.each(selected, item => {

                    if(item.user_id)
                    {
                        if(! _.has(r, item.customer_id))
                        {
                            r[item.customer_id]  = [item.user_id];
                        }
                        else
                        {
                            r[item.customer_id].push(item.user_id);
                        }
                    }
                })

                this.$emit('input', r);
            }
        },

        methods: {

            CreateTree(){

                let tree = _.map(this.customers, item => ({
                    id: item.id,
                    name: item.name,
                    status: item.status,
                    type: 'customer',
                    children: this.GetAccountsById(item.id),
                }));

                tree = _.filter(tree, item => true || item.children.length >= 0);

                this.tree = tree;
            },

            GetAccountsById(customer_id) {
                let accounts = _.filter(this.accounts, item => (item.customer_id == customer_id) && (1 * item.activated == 1) );

                accounts  = _.map(accounts, item => ({
                    id: customer_id + '.' + item.user_id,
                    full_name: item.user.full_name,
                    icon: item.user.icon,
                    initials: item.user.initials,
                    type: 'user',
                    activated: item.activated,
                    role: {
                        id: item.role ? item.role.id : null,
                        slug: item.role ? item.role.slug : null,
                        name: item.role ? item.role.name : null,
                        color: item.role ? item.role.color : null,
                    }
                }))

                accounts = _.orderBy(accounts, [item => item.role.name, item => item.full_name], ['asc', 'asc']);

                return accounts;
            },

            OnCreated() {
                
                this.customersDataProvider.Post();
                this.accountsDataProvider.Post();

                let i = setInterval( () => {
                    if(! this.customersDataProvider.processing && ! this.accountsDataProvider.processing)
                    {
                        clearInterval(i);

                        console.log('Utilizatori, Accounts... OK');

                        this.customers = this.customersDataProvider.items;
                        this.accounts = this.accountsDataProvider.items;

                        this.CreateTree();

                        setTimeout( () => {

                            console.log('OnCreated (' + this.customers.length + ', ' + this.accounts.length + ')');
                            this.$refs.CustomersTree.updateAll(true);
                        }, 300);
                        
                    }
                }, 500);
            }
        },

        created() {
            this.OnCreated(); 
        },

        name: 'CustomersUsersTree',
    }
</script>