<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="0"></Field>

            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Người quản lý</label>
                    <v-select v-model="assignManagerModel.ManagerId" :reduce="(option) => option.Id" label="UserName"
                        :filterable="false" :options="staffs" @search="getStaffs">
                        <template #no-options="{ search, searching, loading }">
                            Gõ từ khóa để tìm....
                        </template>
                        <template v-slot:option="option">

                            {{ option.UserName }} ({{ option.FullName }})
                        </template>
                    </v-select>
                    <Field v-model="assignManagerModel.ManagerId" name="ManagerId" type="hidden" />
                    <ErrorMessage class="invalid-error" name="ManagerId" />
                </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 } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
import _ from 'lodash';



const emit = defineEmits(['changeDate']);
import customerService from "@/services/customerService";
import staffService from "@/services/staffService";
import { useToast } from "vue-toastification";
const toast = useToast();
const loading = ref(false);

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

const staffs = reactive([]);
async function getStaffs(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await sugStaffs(loading, keyword);
    }
}
let sugStaffs = _.debounce(async (loading, keyword) => {
    staffs.splice(0, staffs.length);
    var staffResult = await staffService.sugStaff(keyword);
    if (staffResult != null && staffResult.length > 0) {
        staffResult.forEach(staff => {
            staffs.push(staff);
        });
    }
    loading(false);

}, 300);


let assignManagerModel = reactive({
    Id: 0,
    ManagerId: null,
    ManagerUserName: ''
});

onMounted(() => {
    assignManagerModel.Id = props.id;
    if (props.id > 0) {
        getById(props.id);
    }
})


const schema = Yup.object().shape({
    Id: Yup.number(),
    ManagerId: Yup.number().required('Chọn người quản lý').min(1, 'Chi nhánh không để trống')
});

async function getById(userId) {
    loading.value = true;
    var userResult = await customerService.getManagerById(userId);
    if (userResult.ManagerId > 0) {
        staffs.push({ Id: userResult.ManagerId, UserName: userResult.ManagerUserName, FullName: userResult.ManagerFullName });
        assignManagerModel.ManagerId = userResult.ManagerId;
    } else {
        assignManagerModel.ManagerId = null;
    }
    console.log(staffs);
    loading.value = false;
}


async function onSubmit() {
    console.log(assignManagerModel);
    var result = null;
    result = await customerService.assignManagerById(assignManagerModel);

    if (result != null && result.Result === 1) {
        toast.success('Thành công!');
        cancel();
    } else {
        if (result.ErrorList != null && result.ErrorList.length > 0) {
            toast.error('Thất bại: ' + result.ErrorList.join("\n"));
        } else {
            toast.error('Thất bại: ' + result.Message);
        }

    }

}

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


</script>