<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="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }" class="row">
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Tên menu</label>
                    <Field v-model="menuModel.Label" name="Label" type="text" class="form-control" placeholder="tên menu"
                        :class="{ 'is-invalid': errors.Label }" />
                    <div class="invalid-feedback">{{ errors.Label }}</div>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Menu cha</label>
                    <v-select label="Label" :options="parents" v-model="menuModel.ParentId" :reduce="(option) => option.Id">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <em>{{ search }}</em>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>

                </div>
            </div>

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Loại menu</label>
                    <v-select v-model="menuModel.Kind" label="Name" :options="kinds" :reduce="(option) => option.Id">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <b>{{ search }}</b>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>
                    <Field v-model="menuModel.Kind" name="Kind" type="hidden" />
                    <ErrorMessage class="invalid-error" name="Kind" />
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Ứng dụng</label>
                    <v-select v-model="menuModel.AppType" label="Name" :options="appTypes" :reduce="(option) => option.Id">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <b>{{ search }}</b>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>
                    <Field v-model="menuModel.Kind" name="AppType" type="hidden" />
                    <ErrorMessage class="invalid-error" name="AppType" />
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Đường dẫn</label>
                    <Field v-model="menuModel.Url" name="Url" type="text" class="form-control" placeholder="đường dẫn"
                        :class="{ 'is-invalid': errors.Url }" />
                    <div class="invalid-feedback">{{ errors.Url }}</div>
                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Icon Class</label>
                    <Field v-model="menuModel.IconClass" name="IconClass" type="text" class="form-control"
                        placeholder="icon class" :class="{ 'is-invalid': errors.IconClass }" />
                    <div class="invalid-feedback">{{ errors.IconClass }}</div>
                </div>
            </div>

            <div class="col-4">
                <div class="form-group mb-3">
                    <label>Quyền áp dụng</label>
                    <v-select multiple label="Name" :options="roles" v-model="menuModel.AllowRoles"
                        :reduce="(option) => option.Name">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <b>{{ search }}</b>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>


                </div>
            </div>

            <div class="col-4">
                <div class="form-group mb-3">
                    <label>Thứ tự hiển thị</label>
                    <Field v-model="menuModel.DisplayOrder" name="DisplayOrder" type="number" class="form-control"
                        placeholder="thứ tự hiển thị" :class="{ 'is-invalid': errors.DisplayOrder }" />
                    <ErrorMessage class="invalid-error" name="DisplayOrder" />

                </div>
            </div>
            <div class="col-4">
                <div class="form-group mb-3">
                    <label>Menu Level</label>
                    <v-select label="Name" :options="menuLevels" v-model="menuModel.MenuLevel"
                        :reduce="(option) => option.Id">
                        <template v-slot:no-options="{ search, searching }">
                            <template v-if="searching">
                                Không có kết quả cho <b>{{ search }}</b>.
                            </template>
                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                        </template>
                    </v-select>
                </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>

//#region Imports....
import { ref, onMounted, reactive } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
//#endregion

//#region Services
import roleService from "@/services/roleService";
import menuService from "@/services/menuService";
//#endregion


//#region Toast
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion


//#region props
const props = defineProps({
    id: Number
});
//#endregion

//#region props
//#endregion


const emit = defineEmits(['cancel']);


//#region Models
const loading = ref(false);
const kinds = [
    { Id: 1, Name: 'Group' },
    { Id: 2, Name: 'Has Child' },
    { Id: 3, Name: 'Single' }
];
const parents = reactive([]);
const roles = reactive([]);
const appTypes = reactive([
    { Id: 1, Name: 'Hệ thống quản trị nội bộ' },
    { Id: 8, Name: 'Hệ thống khách hàng' },
    { Id: 2, Name: 'Hệ thống đào tạo' },
    { Id: 3, Name: 'Hệ thống quản lý tài khoản' }
]);

const menuLevels = reactive([
    { Id: 1, Name: 'Level 1' },
    { Id: 2, Name: 'Level 2' },
    { Id: 3, Name: 'Level 3' }
]);

let menuModel = reactive({
    Id: 0,
    Label: '',
    Kind: null,
    Url: '',
    IconClass: '',
    ParentId: null,
    AllowRoles: null,
    AppType: null,
    DisplayOrder: 0,
    MenuLevel: 1
});

async function getRoles() {
    roles.splice(0, roles.length);
    var rolesResult = await roleService.getRoles();
    if (rolesResult != null && rolesResult.length > 0) {
        rolesResult.forEach(role => {
            roles.push(role);
        });
    }
}

async function getParents() {
    parents.splice(0, parents.length);
    var parentResult = await menuService.getTree();
    if (parentResult != null && parentResult.length > 0) {
        parentResult.forEach(menu => {
            parents.push(menu);
        });
    }
}

//#endregion

//#region Validations
const schema = Yup.object().shape({
    Label: Yup.string().required('Tên menu không để trống'),
    Kind: Yup.number().min(1, 'Vui lòng chọn loại menu').required('Vui lòng chọn loại menu'),
    AppType: Yup.number().min(1, 'Vui lòng chọn ứng dụng').required('Vui lòng chọn ứng dụng'),
});
//#endregion

//#region Methods
async function getById(id) {

    var menuResult = await menuService.getById(id);
    menuModel.Id = menuResult.Id;
    menuModel.Label = menuResult.Label;
    menuModel.Url = menuResult.Url;
    menuModel.IconClass = menuResult.IconClass;

    if (menuResult.ParentId == 0) {
        menuModel.ParentId = null;
    } else {
        menuModel.ParentId = menuResult.ParentId;
    }

    if (menuResult.AppType == 0) {
        menuModel.AppType = null;
    } else {
        menuModel.AppType = menuResult.AppType;
    }

    if (menuResult.Kind == 0) {
        menuModel.Kind = null;
    } else {
        menuModel.Kind = menuResult.Kind;
    }

    if (menuResult.AllowRoles != null && menuResult.AllowRoles.length > 0) {
        menuModel.AllowRoles = menuResult.AllowRoles.split(",");
    }

    menuModel.DisplayOrder = menuResult.DisplayOrder;
    menuModel.MenuLevel = menuResult.MenuLevel;

}
async function onSubmit() {
    var postModel = menuModel;
    if (postModel.AllowRoles != null && postModel.AllowRoles.length > 0) {
        postModel.AllowRoles = postModel.AllowRoles.join(",");
    } else {
        postModel.AllowRoles = "";
    }
    postModel.UpdatedByUserName = "";
    postModel.UpdatedBy = 0;
    if (postModel.ParentId == null) {
        postModel.ParentId = 0;
    }
    var menuResult = await menuService.createOrUpdate(postModel);
    if (menuResult != null && menuResult.Result === 1) {
        toast.success('Thành công!');
        cancel();
    } else {
        toast.error('Thất bại: ' + menuResult.Message);
    }

}

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

//#endregion



//#region Events
onMounted(async () => {
    loading.value = true;

    await getRoles();
    await getParents();

    if (props.id > 0) {
        await getById(props.id);
    }
    loading.value = false;
})
//#endregion










</script>