<template>
    <div>
        <Form @submit="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }" class="row">

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Tên quyền</label>
                    <Field v-model="roleModel.Name" name="Name" type="text" class="form-control" placeholder="tên quyền"
                        :class="{ 'is-invalid': errors.Name }" />
                    <div class="invalid-feedback">{{ errors.Name }}</div>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Mô tả</label>
                    <Field v-model="roleModel.Description" name="Description" type="text" class="form-control"
                        placeholder="mô tả" :class="{ 'is-invalid': errors.Description }" />
                    <div class="invalid-feedback">{{ errors.Description }}</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 { onMounted, reactive } from 'vue';
import { Form, Field } from 'vee-validate';
import * as Yup from 'yup';
import roleService from "@/services/roleService";
import { useToast } from "vue-toastification";
const toast = useToast();
const emit = defineEmits(['cancel']);

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

let roleModel = reactive({
    Id: 0,
    Name: '',
    Description: ''
});

const schema = Yup.object().shape({
    Name: Yup.string().required('Tên quyền không để trống'),
    Description: Yup.string().required('Mô tả không để trống'),

});


async function getById(roleId) {
    var roleResult = await roleService.getById(roleId);
    roleModel.Id = roleResult.Id;
    roleModel.Name = roleResult.Name;
    roleModel.Description = roleResult.Description;
}




async function onSubmit() {
    roleModel.UpdatedByUserName = "";
    roleModel.UpdatedBy = 0;
    var createResult = await roleService.createOrUpdate(roleModel);
    cancel();
    if (createResult != null && createResult.Result === 1) {
        toast.success('Thành công!');
    } else {
        toast.error('Thất bại: ' + createResult.message);
    }

}

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


onMounted(() => {
    console.log('Ma role: ' + props.id);
    if (props.id > 0) {
        getById(props.id);
    }

})
</script>