<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">
            <Field name="Id" type="hidden" :value="agencyModel.Id"></Field>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Tên chi nhánh</label>
                    <Field v-model="agencyModel.Name" name="Name" type="text" class="form-control"
                        placeholder="tên chi nhánh" :class="{ 'is-invalid': errors.Name }" />
                    <div class="invalid-feedback">{{ errors.Name }}</div>
                </div>
            </div>
            <div class="col-3">
                <div class="form-group mb-3">
                    <label>Mã chi nhánh</label>
                    <Field v-model="agencyModel.Code" name="Code" type="text" class="form-control"
                        placeholder="mã chi nhánh" :class="{ 'is-invalid': errors.Code }" />
                    <div class="invalid-feedback">{{ errors.Code }}</div>
                </div>
            </div>
            <div class="col-3">
                <div class="form-group mb-3">
                    <label>Thứ tự hiển thị</label>
                    <Field v-model="agencyModel.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-6">
                <div class="form-group mb-3">
                    <label>Chi nhánh cha</label>
                    <v-select label="Label" :options="parents" v-model="agencyModel.ParentId"
                        :reduce="(option) => option.Id" :class="{ 'is-invalid': errors.ParentId }">
                        <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>
                    <Field v-model="agencyModel.ParentId" name="ParentId" type="hidden" />
                    <ErrorMessage class="invalid-error" name="ParentId" />

                </div>
            </div>
            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Mô tả</label>
                    <Field v-model="agencyModel.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 mb-3">
                <CityDistrictWard v-model:city-id="agencyModel.CityId" v-model:district-id="agencyModel.DistrictId"
                    v-model:ward-id="agencyModel.WardId">
                </CityDistrictWard>
            </div>
            <div class="col-8">
                <div class="form-group mb-3">
                    <label>Địa chỉ</label>
                    <Field v-model="agencyModel.Address" name="Address" type="text" class="form-control"
                        placeholder="địa chỉ" :class="{ 'is-invalid': errors.Address }" />
                    <div class="invalid-feedback">{{ errors.Address }}</div>
                </div>
            </div>
            <div class="col-4">
                <div class="form-group mb-3">
                    <label>Loại chi nhánh</label>
                    <v-select label="Name" :options="agencyTypes" v-model="agencyModel.AgencyType"
                        :reduce="(option) => option.Id" :clearable="false" :class="{ 'is-invalid': errors.AgencyType }">
                        <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>
                    <Field v-model="agencyModel.AgencyType" name="AgencyType" type="hidden" />
                    <ErrorMessage class="invalid-error" name="AgencyType" />
                </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 Components
import CityDistrictWard from "@/components/locations/CityDistrictWard.vue";
//#endregion

//#region Services
import agencyService from "@/services/agencyService";
//#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 parents = reactive([]);
const roles = reactive([]);
const agencyTypes = [
    { Id: 1, Name: 'Phòng ban của LADA' },
    { Id: 2, Name: 'Chi nhánh nhượng quyền' },
    { Id: 3, Name: 'Chi nhánh của LADA' }
];

let agencyModel = reactive({
    Id: 0,
    Name: '',
    Description: '',
    CityId: null,
    DistrictId: null,
    WardId: null,
    Address: '',
    Code: '',
    ParentId: null,
    DisplayOrder: 0,
    AgencyType: 1
});


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

//#endregion

//#region Validations
const schema = Yup.object().shape({
    Id: Yup.number(),
    Name: Yup.string().required('Tên chi nhánh không để trống'),
    Code: Yup.string().required('Mã chi nhánh không để trống'),
    Address: Yup.string().required('Địa chỉ không để trống'),
    DisplayOrder: Yup.number().min(0, 'Thứ tự hiển thị phải lớn hơn hoặc bằng 0').notRequired(),
    ParentId: Yup.number().nullable(),
    AgencyType: Yup.number().required('Chọn loại chi nhánh')


});
//#endregion

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

    var agencyResult = await agencyService.getById(id);
    agencyModel.Id = agencyResult.Id;
    agencyModel.Name = agencyResult.Name;
    agencyModel.Description = agencyResult.Description;
    agencyModel.Code = agencyResult.Code;
    agencyModel.ParentId = agencyResult.ParentId > 0 ? agencyResult.ParentId : null;

    agencyModel.DisplayOrder = agencyResult.DisplayOrder;
    agencyModel.CityId = agencyResult.CityId;
    agencyModel.DistrictId = agencyResult.DistrictId;
    agencyModel.WardId = agencyResult.WardId;
    agencyModel.Address = agencyResult.Address;
    if (agencyResult.AgencyType == null || agencyResult.AgencyType == 0) {
        agencyModel.AgencyType = 1;
    } else {
        agencyModel.AgencyType = agencyResult.AgencyType;
    }

}
async function onSubmit() {
    var postModel = agencyModel;
    console.log(postModel);

    postModel.UpdatedByUserName = "";
    postModel.UpdatedBy = 0;
    if (postModel.ParentId == null) {
        postModel.ParentId = 0;
    }
    var agencyResult = await agencyService.createOrUpdate(postModel);
    if (agencyResult != null && agencyResult.Result === 1) {
        toast.success('Thành công!');
        cancel();
    } else {
        toast.error('Thất bại: ' + agencyResult.Message);
    }

}

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

//#endregion




//#region Events
onMounted(async () => {
    loading.value = true;
    await getParents();
    if (props.id > 0) {
        await getById(props.id);
    }
    loading.value = false;
})
//#endregion










</script>

<style>
fieldset {
    border: 1px solid #555;
}

fieldset legend {
    font-size: inherit;
    line-height: 30px;
    font-weight: 600;
    text-transform: uppercase;
    color: #555;
}
</style>