<template>
    <v-dialog v-model="modal" persistent max-width="700">
        <v-card>
            <v-card-title>
                <v-row justify="end" class="pt-2"><v-hover v-slot="{ isHovering, props }"><v-icon size="small" v-bind="props" :color="isHovering ? 'grey-darken-1' : 'grey-lighten-1'" variant="plain" icon="mdi-close" @click="closeDialog()"></v-icon></v-hover></v-row>
            </v-card-title>

            <v-card-text>

                <v-row class="d-flex pb-8">
                    <v-col align="center" cols="12" class="pb-0">
                        <v-avatar color="yellow-darken-1" size="80">
                            <v-icon size="50" icon="mdi-account-edit" color="white"></v-icon>
                        </v-avatar>
                    </v-col>
                    <v-col align="center" cols="12" style="font-size: 25px;color:#FDD835" class="pt-0 mt-0"><strong>Edit User</strong></v-col>
                </v-row>

                <v-row wrap no-gutters>
                    <v-col cols="5" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="2" class="text-center">
                        User Details
                    </v-col>
                    <v-col cols="5" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>

                <v-row>
                    <v-col cols="6">
                        <v-text-field type="text" v-model="firstname" label="First name*" v-on:input="handleFirstnameLastnameChange" ref="firstname" :error="isError('firstname')" :error-messages="isErrorMessage('firstname')"></v-text-field>
                    </v-col>
                    <v-col cols="6">
                        <v-text-field type="text" v-model="lastname" label="Last name*" v-on:input="handleFirstnameLastnameChange" ref="lastname" :error="isError('lastname')" :error-messages="isErrorMessage('lastname')"></v-text-field>
                    </v-col>
                    <v-col cols="6">
                        <v-text-field type="text" v-model="personalEmail" label="Personal E-mail*" ref="personalEmail" :error="isError('personalEmail')" :error-messages="isErrorMessage('personalEmail')"></v-text-field>
                    </v-col>
                    <v-col cols="6">
                        <v-text-field type="text" v-model="workEmail" label="Work E-mail*" ref="workEmail" :error="isError('workEmail')" :error-messages="isErrorMessage('workEmail')"></v-text-field>
                    </v-col>
                </v-row>

                <v-row wrap no-gutters>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="4" class="text-center">
                        User Job Role
                    </v-col>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>

                <v-row>
                    <v-col cols="12">
                        <v-select v-model="NewUserJobRole" :items="jobRoles" item-title="name" item-value="id" label="Job Role"></v-select>
                    </v-col>
                </v-row>

                <v-row wrap no-gutters>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="4" class="text-center">
                        Assigned Tools
                    </v-col>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>

                <v-row class="my-4 d-flex">
                    <v-col style="font-size: 15px;" class="py-0" cols="4" v-for="(assignedTool, i) in assignedTools" :key="i">
                        <v-icon class="pt-0 mt-0" size="14" icon="mdi-cog"></v-icon> 
                        <span v-if="assignedTool.status == 2" style="text-decoration: line-through">{{ assignedTool.name }}</span>
                        <span v-if="assignedTool.status == 0 || assignedTool.status == 1">{{ assignedTool.name }}</span>
                        <v-icon v-if="assignedTool.status == 0 || assignedTool.status == 1" class="pt-0 mt-0" size="small" icon="mdi-close" color="red" variant="plain" @click="deleteTool(assignedTool.ID)"></v-icon> 
                    </v-col>
                </v-row>

                <v-row wrap no-gutters>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                    <v-col cols="4" class="text-center">
                        Additional Tools
                    </v-col>
                    <v-col cols="4" class="text-center">
                        <v-divider class="mt-3" />
                    </v-col>
                </v-row>

                <v-row v-for="(AdditionalTool, i) in AdditionalTools" :key="i" class="text-fields-row">
                    <v-col cols="6" >
                        <v-select label="Tool" v-model="AdditionalTool.tool" :items="tools" item-title="name" item-value="id" variant="solo-filled"></v-select>
                    </v-col>
                    <v-col cols="6" >
                        <v-select label="Tool Role" v-model="AdditionalTool.role" :items="ToolsWithRoles[AdditionalTool.tool]" item-title="option" item-value="id" variant="solo-filled" multiple>
                            <template v-slot:append>
                                <v-hover v-slot="{ isHovering, props }">       
                                    <v-icon v-bind="props" :color="isHovering ? 'red-accent-2' : 'red-accent-4'" @click="removeTool(i)">mdi-trash-can-outline</v-icon> 
                                </v-hover> 
                            </template>
                            <template v-slot:selection="{ item, index }">
                                <v-chip v-if="index < 2">
                                    <span>{{ item.title }}</span>
                                </v-chip>
                                <span v-if="index === 2" class="text-grey text-caption align-self-center">
                                    (+{{ AdditionalTools[i].role.length - 2 }})
                                </span>
                            </template>
                        </v-select>
                    </v-col>
                </v-row>
                <v-btn variant="text" @click="addToolToRole()" class="primary" color="green" prepend-icon="mdi-plus">Add Tool</v-btn>

            </v-card-text>
            <v-divider class="mt-5"></v-divider>
            <v-card-actions>
                <v-btn color="red darken-1" text @click="closeDialog()">
                    Close
                </v-btn>
                <v-spacer></v-spacer>
                <v-btn color="green darken-1" text @click="saveUser()">
                    Save
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog> 
</template>
<script scoped>
    export default {
        expose: ['showDialog'],
        data: () => ({
            modal: false,

            userID: '',
            firstname:'',
            lastname:'',
            personalEmail:'',
            workEmail:'',
            NewUserJobRole:0,
            AdditionalTools:[],
            ToolsDelete:[],

            jobRoles:[],
            ToolsWithRoles:[],
            tools:[],
            assignedTools:[],

            errors:{},
            errorsMessages:{},
        }),

        watch: {
            NewUserJobRole(newValue, oldValue) {
                //this.loadAssignedTools();
            },
        },

        methods: {
            async showDialog(ID) {
                this.userID = ID;
                this.$root.$refs.overlay.showOverlay(true);
                if (await this.loadUserDetails(ID) === 'Success') {
                    if (await this.loadJobRoles() === 'Success') {
                        //this.loadAssignedTools();
                        this.loadToolsWithRoles();
                        this.loadTools();
                        this.modal = true;
                    }
                }
                this.$root.$refs.overlay.showOverlay(false);
            },

            closeDialog()
            {
                this.modal = false;
                this.userID = '';
                this.firstname = '';
                this.lastname = '';
                this.personalEmail = '';
                this.workEmail = '';
                this.NewUserJobRole = 0;
                this.AdditionalTools = [];
                this.errors = {};
                this.errorsMessages = {};
                this.ToolsDelete = [];
            },

            addToolToRole() {
                this.AdditionalTools.push({
                    tool: "",
                    role: [],
                })
            },

            removeTool(index) {
                this.AdditionalTools.splice(index, 1)
            },

            isError(fieldName) {
                return this.errors[fieldName];
            },

            isErrorMessage(fieldName) {
                return this.errorsMessages[fieldName];
            },

            saveUser() {
                this.$root.$refs.overlay.showOverlay(true);
                this.errors = {};
                this.errorsMessages = {};
                let response;
                let params = {
                    firstname: this.firstname,
                    lastname: this.lastname,
                    personalEmail: this.personalEmail,
                    workEmail: this.workEmail,
                    NewUserJobRole: this.NewUserJobRole,
                    AdditionalTools: this.AdditionalTools,
                    ToolsDelete: this.ToolsDelete,
                };

                console.log(params);

                
                this.$root.axiosPost('/users-manager/edit/'+this.userID, params).then(data => {
                    response = data.response.data;
                    this.$root.$refs.overlay.showOverlay(false);
                    if (response.status === 'Error') {
                        if (response.message === 'Validation Error.') {
                            response.data.forEach((el, index) => {
                                Object.entries(el).forEach((el1, index1) => {
                                    this.errors[el1[0]] = !this.isError(el1[0]);
                                    this.errorsMessages[el1[0]] = el1[1];
                                });
                            });
                        }
                    } else {
                        this.$emit('load-users');
                        this.closeDialog();
                    }
                });
            },

            loadAssignedTools() {
                this.loadingAssignedTools = true;
                let roleID = this.NewUserJobRole;

                if (roleID == '') {
                    roleID = 0;
                }

                this.$root.axiosGet('/role-manager-load-job-roles/'+roleID+'/tools').then(data => {
                    this.loadingAssignedTools = false;
                    this.assignedTools = data.response.data.data;
                });
            },

            loadJobRoles() {
                let response;
                return new Promise((resolve, reject) => {
                    this.$root.axiosGet('/role-manager-load').then(data => {
                        response = data.response.data;
                        this.jobRoles = response.data;
                        this.jobRoles.unshift({id:0, name:'None'});
                        resolve(response.status);
                    }); 
                });
            },

            loadToolsWithRoles() {
                this.$root.axiosGet('/role-manager-load-tools-roles').then(data => {
                    this.ToolsWithRoles = data.response.data.data;
                }); 
            },

            loadTools() {
                this.$root.axiosGet('/role-manager-load-nodefault-tools').then(data => {
                    this.tools = data.response.data.data;
                }); 
            },

            deleteTool(ID) { 
                console.log(ID)
                this.ToolsDelete.push({
                    tool: ID,
                });

                this.assignedTools.forEach((el, index) => {
                if (parseInt(el.ID) === parseInt(ID)) {
                    this.assignedTools[index].status = 2;
                }
            });
            },

            async loadUserDetails(ID) {
                let response;
                return new Promise((resolve, reject) => {
                    this.$root.axiosGet('/users-manager/info/'+ID).then(data => {
                        response = data.response.data;

                        this.firstname = response.data.userDetails.firstname;
                        this.lastname = response.data.userDetails.lastname;
                        this.personalEmail = response.data.userDetails.personalEmail;
                        this.workEmail = response.data.userDetails.email;
                        this.NewUserJobRole = response.data.userDetails.jobRole;
                        this.assignedTools = response.data.userTools;

                        resolve(response.status);
                    }); 
                });
            },

            handleFirstnameLastnameChange() {
                //this.workEmail = this.firstname.toLowerCase() +'.'+this.lastname.toLowerCase()+'@hostafrica.com'
            },
        }
    }
</script>