<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">{{ pageTitle }}</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item">
                        <router-link :to="{ name: 'home' }">
                            Trang chủ
                        </router-link>
                    </li>
                    <li class="breadcrumb-item">

                        <router-link :to="{ name: 'hr-job' }">
                            Tuyển dụng
                        </router-link>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page">{{ pageTitle }}</li>
                </ol>
            </div>
        </div>
        <div class="row g-0">
            <Form ref="formRef" @submit="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }"
                class="row">
                <div class="col-12">
                    <div class="card shadow-sm mg-b-10">
                        <div class="card-body p-3">
                            <div class="d-flex flex-row justify-content-between">
                                <router-link class="btn btn-link button-icon" :to="{ name: 'hr-job' }">
                                    <i class="fe fe-arrow-left me-2"></i>Danh sách tin tuyển dụng
                                </router-link>
                                <div>
                                    <button type="submit" class="btn btn-primary button-icon">
                                        <i class="fe fe-save me-2"></i>Lưu lại
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-12">
                    <div class="card shadow-none rounded-0" style="min-height: 100vh;">
                        <div class="card-body">
                            <div class="col-lg-12">
                                <div class="row">
                                    <div class="col-lg-9">
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="form-group mb-3">
                                                    <label>Tiêu đề tin tuyển dụng:</label>
                                                    <Field v-model="postModel.Title" name="Title" type="text"
                                                        class="form-control" placeholder="tiêu đề tin tuyển dụng"
                                                        :class="{ 'is-invalid': errors.Title }" />
                                                    <div class="invalid-feedback">{{ errors.Title }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Loại hình công việc:</label>
                                                    <v-select label="Name" :options="jobTypes"
                                                        v-model="postModel.JobType" :reduce="(option) => option.Id"
                                                        :class="{ 'is-invalid': errors.JobType }">
                                                        <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="postModel.JobType" name="JobType" type="hidden" />
                                                    <div class="invalid-feedback">{{ errors.JobType }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Phòng ban:</label>
                                                    <Field v-model="postModel.Department" name="Department" type="text"
                                                        class="form-control" placeholder="phòng ban"
                                                        :class="{ 'is-invalid': errors.Department }" />
                                                    <div class="invalid-feedback">{{ errors.Department }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Vị trí:</label>
                                                    <Field v-model="postModel.Position" name="Position" type="text"
                                                        class="form-control" placeholder="vị trí"
                                                        :class="{ 'is-invalid': errors.Position }" />
                                                    <div class="invalid-feedback">{{ errors.Position }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Thu nhập từ:</label>

                                                    <Field v-model="postModel.MinSalary" name="MinSalary" type="text"
                                                        class="form-control" placeholder="thu nhập tới..."
                                                        :class="{ 'is-invalid': errors.MinSalary }" />
                                                    <div class="invalid-feedback">{{ errors.MinSalary }}</div>

                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Thu nhập đến:</label>
                                                    <Field v-model="postModel.MaxSalary" name="MaxSalary" type="text"
                                                        class="form-control" placeholder="thu nhập tới..."
                                                        :class="{ 'is-invalid': errors.MaxSalary }" />
                                                    <div class="invalid-feedback">{{ errors.MaxSalary }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Địa chỉ làm việc:</label>
                                                    <Field v-model="postModel.WorkingAddress" name="WorkingAddress"
                                                        type="text" class="form-control" placeholder="địa chỉ làm việc"
                                                        :class="{ 'is-invalid': errors.WorkingAddress }" />
                                                    <div class="invalid-feedback">{{ errors.WorkingAddress }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Email:</label>
                                                    <Field v-model="postModel.Email" name="Email" type="text"
                                                        class="form-control" placeholder="email nhận cv"
                                                        :class="{ 'is-invalid': errors.Email }" />
                                                    <div class="invalid-feedback">{{ errors.Email }}</div>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group mb-3">
                                                    <label>Ngày bắt đầu - kết thúc:</label>
                                                    <VueDatePicker ref="startEndDatePicker" v-model="startEndDate"
                                                        :min-date="new Date()" :enable-time-picker="false" range
                                                        multi-calendars auto-apply :format="format"
                                                        @update:model-value="handleDate">
                                                        <template #left-sidebar>
                                                            <DateRangeSidebar @change-date="onChangeDate">
                                                            </DateRangeSidebar>
                                                        </template>
                                                    </VueDatePicker>
                                                    <div class="invalid-feedback">{{ errors.StartDate }}</div>
                                                    <div class="invalid-feedback">{{ errors.EndDate }}</div>

                                                </div>
                                            </div>
                                            <div class="col-lg-12">
                                                <Tags ref="tagRef"></Tags>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-3">
                                        <label>Ảnh đại diện:</label>
                                        <FeaturedPicture ref="featuredPictureRef"></FeaturedPicture>
                                    </div>

                                    <div class="col-12 mt-3">

                                        <div class="form-group">
                                            <label>Nội dung công việc:</label><br>

                                            <button @click="addPicture" type="button"
                                                class="btn btn-sm btn-outline-secondary button-icon mb-2">
                                                <i class="fe fe-camera me-2"></i>Thêm ảnh
                                            </button>

                                            <editor v-model="postModel.Description" :init="editorStore.init"
                                                :toolbar="editorStore.toolbar" :plugins="editorStore.plugins"
                                                style="min-height:535px;">
                                            </editor>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        </div>

    </div>
</template>
<script setup>


import { ref, onMounted, reactive } from 'vue';

import moment from "moment";

import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';
import { useEditorStore } from '@/stores';
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';

import Tags from './components/Tags.vue';


import { useRouter } from 'vue-router';
const router = useRouter();

//#region props
const props = defineProps({
    id: {
        type: String,
        default: ''
    }
});
//#endregion

//#region components


//#region Toast
import { useToast } from "vue-toastification";
const toastOption = {

};
const toast = useToast();
//#endregion


//#endregion

//#region Services
import jobService from "@/services/jobService";
import postService from "@/services/postService";
import pictureService from "@/services/pictureService";
//#endregion


//#region DATA
import FeaturedPicture from './components/FeaturedPicture.vue';
const featuredPictureRef = ref(null);
const tagRef = ref(null);

var config = {
    decimal: ",",
    thousands: ".",
    prefix: "",
    suffix: "đ",
    precision: 0,
    masked: false /* doesn't work with directive */,
};

//#region Start/End Date
const startEndDate = ref();
const startEndDatePicker = ref(DatepickerInstance);
function handleDate(modelData) {
    if (modelData != null) {
        postModel.StartDate = modelData[0];
        postModel.EndDate = modelData[1];
    } else {
        postModel.StartDate = null;
        postModel.EndDate = null;
    }
}
async function onChangeDate(newDates) {
    startEndDate.value = newDates;
    startEndDatePicker.value.closeMenu();
    handleDate(newDates)
}
const format = (dates) => {
    let start = dates[0];
    let end = dates[1];

    var startMoment = moment(start);
    var endMoment = moment(end);

    return `${startMoment.format("DD/MM/yyyy")} - ${endMoment.format("DD/MM/yyyy")}`;
}
//#endregion

const editorStore = useEditorStore();

//#region Validations
const schema = Yup.object().shape({
    Title: Yup.string().required('Tiêu đề tin tuyển dụng không để trống'),
    JobType: Yup.number().min(1, 'Vui lòng chọn loại hình công việc').required('Vui lòng chọn loại hình công việc')
});
//#endregion


const loading = ref(false);

const jobTypes = [
    { Id: 10, Name: 'Toàn thời gian' },
    { Id: 20, Name: 'Bán thời gian' },
    { Id: 30, Name: 'Thực tập' }
];


let postModel = reactive({
    Id: 0,
    Thumbnail: '',
    Title: '',
    Description: '',
    WorkingAddress: '',
    JobType: 10,
    MinSalary: 0,
    MaxSalary: 0,
    Department: '',
    Position: '',
    StartDate: null,
    EndDate: null,
    Email: '',
    JobStatus: 10,
    Tags: [],
});

const pageTitle = ref("Tạo tin tuyển dụng");

//#endregion

//#region Methods
const handleValidate = () => {
    console.log("Gọi validate");
}


async function send() {

}

const addPicture = async () => {
    var selectedFile = null;
    var input = document.createElement('input');
    input.type = 'file';
    input.click();
    input.onchange = e => {
        selectedFile = e.target.files[0];
        uploadJobContentPicture(selectedFile);
    }
};

const uploadJobContentPicture = async (selectedFile) => {

    const formData = new FormData();
    formData.append(selectedFile.name, selectedFile);
    var uploadResult = await pictureService.uploadJobPostContentPicture(formData);
    if (uploadResult != null && uploadResult.Result === 1) {
        postModel.Description += '<img src="' + uploadResult.Url + '">';
    } else {
        toast.error('Thất bại: ' + uploadResult.Message);
    }

};

async function getById(id) {
    var postId = parseInt(id);
    var postResult = await jobService.getById(postId);
    postModel.Id = postResult.Id;
    postModel.Title = postResult.Title;
    postModel.Description = postResult.Description;
    postModel.Thumbnail = postResult.Thumbnail;
    postModel.Department = postResult.Department;
    postModel.Position = postResult.Position;
    postModel.MinSalary = postResult.MinSalary;
    postModel.MaxSalary = postResult.MaxSalary;
    postModel.WorkingAddress = postResult.WorkingAddress;
    postModel.JobType = postResult.JobType;
    postModel.Email = postResult.Email;
    postModel.StartDate = postResult.StartDate;
    postModel.EndDate = postResult.EndDate;
    postModel.Tags = postResult.Tags;
    startEndDate.value = [postModel.StartDate, postModel.EndDate];
    featuredPictureRef.value.init(postModel);
    tagRef.value.init(postModel);
}




async function onSubmit() {
    var featuredPicture = await featuredPictureRef.value.onSubmit();
    postModel.Thumbnail = featuredPicture.Thumbnail;
    var tags = await tagRef.value.onSubmit();
    postModel.Tags = tags;
    var postResult = await jobService.createOrUpdate(postModel);
    if (postResult != null && postResult.Result === 1) {
        toast.success('Thành công!');
        if (postModel.Id <= 0) {
            router.push({ name: 'hr-job-update', params: { id: postResult.Id } });
        } else {
            await getById(postModel.Id);
        }

    } else {
        toast.error('Thất bại: ' + postResult.Message);
    }
}


//#endregion

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

        await getById(props.id);
        console.log('After jobService.getById:' + featuredPictureRef.value);
        pageTitle.value = "Cập nhật tin tuyển dụng";
        console.log('da vao day');
    } else {
        pageTitle.value = "Tạo tin tuyển dụng";
    }

    loading.value = false;
})
//#endregion

</script>
