<template>
    <div class="modal-body">
        <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>Họ và tên <span class="text-danger">*</span></label>
                    <Field v-model="leadModel.FullName" name="FullName" type="text" class="form-control"
                        placeholder="Nhập họ và tên" :class="{ 'is-invalid': errors.FullName }" />
                    <div class="invalid-feedback">{{ errors.FullName }}</div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group mb-3">
                    <label>Số điện thoại <span class="text-danger">*</span></label>
                    <Field v-model="leadModel.PhoneNumber" name="PhoneNumber" type="tel" class="form-control"
                        placeholder="Nhập số điện thoại" :class="{ 'is-invalid': errors.PhoneNumber }" />
                    <div class="invalid-feedback">{{ errors.PhoneNumber }}</div>
                </div>
            </div>

            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Lời nhắn</label>
                    <textarea v-model="leadModel.Message" name="Message" class="form-control" rows="4"
                        placeholder="Nhập lời nhắn từ khách hàng"></textarea>
                </div>
            </div>

            <div class="col-12">
                <div class="form-group mb-3">
                    <label>Ghi chú</label>
                    <textarea v-model="leadModel.StatusContent" name="StatusContent" class="form-control" rows="3"
                        placeholder="Nhập ghi chú nội bộ"></textarea>
                </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>
                        Tạo lead
                    </button>
                </div>
            </div>
        </Form>
    </div>
</template>

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

//#region Services
import leadService from "@/services/crm/leadService";
//#endregion

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

const loading = ref(false);
const emit = defineEmits(['cancel', 'success']);

//#region Models
let leadModel = reactive({
    FullName: '',
    PhoneNumber: '',
    Email: '',
    SourcePath: '',
    Message: '',
    StatusContent: ''
});
//#endregion

//#region Validations
const schema = Yup.object().shape({
    FullName: Yup.string().required('Họ và tên không được để trống'),
    PhoneNumber: Yup.string()
        .required('Số điện thoại không được để trống')
        .matches(/^0[0-9]{9,10}$/, 'Số điện thoại phải bắt đầu bằng 0 và có 10-11 chữ số')
});
//#endregion

//#region Methods
async function onSubmit() {
    var paramModel = leadModel;
    var leadResult = await leadService.createOrUpdate(paramModel);

    if (leadResult != null && leadResult.Result === 1) {
        toast.success('Tạo lead thành công!');
        resetForm();
        emit('success');
    } else {
        if (leadResult.ErrorList && leadResult.ErrorList.length > 0) {
            toast.error('Thất bại: ' + leadResult.ErrorList.join("\n"));
        } else {
            toast.error('Thất bại: ' + (leadResult.Message || 'Có lỗi xảy ra'));
        }
    }
}

function resetForm() {
    leadModel.FullName = '';
    leadModel.PhoneNumber = '';
    leadModel.Email = '';
    leadModel.SourcePath = window.location.href;
    leadModel.Message = '';
    leadModel.StatusContent = '';
}

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

function setSourcePath() {
    leadModel.SourcePath = window.location.href;
}
//#endregion

//#region Events
onMounted(() => {
    setSourcePath();
});
//#endregion
</script>

<style scoped>
.form-label {
    font-weight: 500;
    margin-bottom: 0.5rem;
}

.text-danger {
    color: #dc3545 !important;
}

.invalid-feedback {
    display: block;
    width: 100%;
    margin-top: 0.25rem;
    font-size: 0.875em;
    color: #dc3545;
}

.is-invalid {
    border-color: #dc3545;
    padding-right: calc(1.5em + 0.75rem);
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='m5.8 4.6 2.4 2.4m0-2.4L5.8 7'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
</style>