<template>
    <div>
        <div v-if="loading" class="row">
            <div class="col-12 tx-semibold text-center text-default">
                <span class="spinner-border spinner-border-sm"></span>
            </div>
        </div>
        <Form v-if="!loading" @submit.prevent="onSubmit" :validation-schema="schema" class="row">

            <div class="row">
                <div class="col-12">
                    <div class="form-group mb-3">
                        <label>Chọn vai trò</label>
                        <v-select v-model="selectedPermissionId" :reduce="(option) => option.Id" label="Name"
                            :options="permissions">
                            <template #no-options="{ search, searching, loading }">
                                Gõ từ khóa để tìm....
                            </template>
                        </v-select>
                        <span v-if="setPermissionModel.PermissionId <= 0" role="alert" class="invalid-error">
                            Vai trò không để trống
                        </span>


                    </div>
                </div>

            </div>


            <div class="col-12 ">
                <div class="d-flex flex-row-reverse">
                    <button @click="cancel" type="button" class="btn btn-main-default mg-l-15">
                        Bỏ qua
                    </button>
                    <button type="submit" class="btn btn-main-primary" :disabled="isSubmitting">
                        <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                        Xác nhận
                    </button>
                </div>
            </div>
        </Form>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import permissionService from "@/services/permissionService";
const emit = defineEmits(['cancel']);

import * as Yup from 'yup';


import { useToast } from "vue-toastification";
const toast = useToast();

const loading = ref(false);
const isSubmitting = ref(false);

const permissions = reactive([]);

const props = defineProps({
    id: Number,
    permissionId: Number
});

let setPermissionModel = reactive({
    UserId: 0,
    PermissionId: 0
});

const selectedPermissionId = ref();


const schema = Yup.object().shape({
    PermissionId: Yup.number().required('Vai trò không để trống')
});

async function getPermissions() {
    loading.value = true;
    permissions.splice(0, permissions.length);

    var permissionsResult = await permissionService.getPermissions();
    // var searchResult = await userService.listStaff(searchModel);
    if (permissionsResult != null && permissionsResult.length > 0) {
        permissionsResult.forEach(permission => {
            permissions.push(permission);
        });
    }

    loading.value = false;
}


async function onSubmit() {
    isSubmitting.value = true;
    if (setPermissionModel.UserId > 0 && setPermissionModel.PermissionId > 0) {
        var setPermissionResult = null;
        setPermissionResult = await permissionService.setPermission(setPermissionModel);

        if (setPermissionResult != null && setPermissionResult.Result === 1) {
            toast.success('Thành công!');
            cancel();
        } else {
            if (setPermissionResult.ErrorList != null && setPermissionResult.ErrorList.length > 0) {
                toast.error('Thất bại: ' + setPermissionResult.ErrorList.join("\n"));
            } else {
                toast.error('Thất bại: ' + setPermissionResult.Message);
            }
        }
    } else {
        toast.error('Thất bại: Vai trò không để trống');
    }
    isSubmitting.value = false;
}



function cancel() {
    emit('cancel');
}



onMounted(async () => {
    console.log('vao mounted');
    await getPermissions(permissions);
    setPermissionModel.UserId = props.id;
    selectedPermissionId.value = props.permissionId;
})

watch(selectedPermissionId, async (newPermissionId) => {

    if (newPermissionId === 0 || newPermissionId === null) {
        setPermissionModel.PermissionId = 0;
    } else {
        if (permissions != null && permissions.length > 0) {
            permissions.forEach(permission => {
                if (permission.Id === selectedPermissionId.value) {
                    setPermissionModel.PermissionId = permission.Id;
                }
            });
        }
    }

})

</script>