<!-- page:จัดการรอบการสอบแข่งขัน สรรหา -->
<template>
	<div class="toptitle text-dark col-12 row items-center">
		<q-btn
			icon="mdi-arrow-left"
			unelevated
			round
			dense
			flat
			color="primary"
			class="q-mr-sm"
			@click="clickBack"
		/>
		{{ edit ? "แก้ไขรอบสอบแข่งขัน" : "เพิ่มรอบสอบแข่งขัน" }}
	</div>
	<q-card flat bordered class="col-12">
		<q-form ref="myForm">
			<q-card-section class="q-pa-md">
				<div class="col-xs-12 col-sm-8"></div>
				<div class="col-12 row items-center q-col-gutter-x-sm">
					<div class="col-xs-12 col-sm-8">
						<q-input
							outlined
							v-model="name"
							label="ชื่อรอบสอบแข่งขัน"
							dense
							lazy-rules
							:rules="[
								(val) =>
									!!val || `${'กรุณากรอกชื่อรอบสอบแข่งขัน'}`,
							]"
						></q-input>
					</div>
					<div
						class="col-xs-12 col-sm-4 col-md-1"
						v-if="announcementExam"
					>
						<q-input
							outlined
							v-model="round"
							type="number"
							label="รอบการสอบ(ครั้ง)"
							dense
							lazy-rules
							:rules="[
								(val) =>
									val > 0 ||
									`${'กรุณากรอกรอบการสอบให้ถูกต้อง'}`,
							]"
						></q-input>
					</div>
					<div
						class="col-xs-12 col-sm-4 col-md-1"
						v-if="announcementExam"
					>
						<datepicker
							menu-class-name="modalfix"
							v-model="yearly"
							:locale="'th'"
							autoApply
							year-picker
							:enableTimePicker="false"
							@update:modelValue="updateYear"
						>
							<template #year="{ year }">{{
								year + 543
							}}</template>
							<template #year-overlay-value="{ value }">{{
								parseInt(value + 543)
							}}</template>
							<template #trigger>
								<q-input
									dense
									lazy-rules
									outlined
									:model-value="yearly + 543"
									:rules="[
										(val) =>
											!!val ||
											`${'กรุณาเลือกปีงบประมาณ'}`,
									]"
									:label="`${'ปีงบประมาณ'}`"
								>
									<template v-slot:prepend>
										<q-icon
											name="event"
											class="cursor-pointer"
											style="color: var(--q-primary)"
										>
										</q-icon>
									</template>
								</q-input>
							</template>
						</datepicker>
					</div>
					<div
						class="col-xs-12 col-sm-4 col-md-2"
						v-if="announcementExam"
					>
						<q-input
							outlined
							v-model="fee"
							type="number"
							label="ค่าธรรมเนียม"
							dense
							lazy-rules
							input-class="text-right"
							:rules="[
								(val) =>
									val >= 0 ||
									`${'กรุณากรอกค่าธรรมเนียมให้ถูกต้อง'}`,
							]"
						></q-input>
					</div>
					<div
						class="col-xs-12 col-sm-3 col-md-3"
						v-if="announcementExam"
					>
						<datepicker
							menu-class-name="modalfix"
							v-model="dateExam"
							:locale="'th'"
							autoApply
							borderless
							:enableTimePicker="false"
							week-start="0"
						>
							<template #year="{ year }">
								{{ year + 543 }}
							</template>
							<template #year-overlay-value="{ value }">
								{{ parseInt(value + 543) }}
							</template>
							<template #trigger>
								<q-input
									outlined
									dense
									class="full-width datepicker q-mb-md"
									:model-value="
										dateExam != null
											? date2Thai(dateExam)
											: null
									"
									:label="`${'วันที่สอบ'}`"
									:rules="[
										(val) =>
											!!val || `${'กรุณาเลือกวันที่สอบ'}`,
									]"
								>
									<template v-slot:prepend>
										<q-icon
											name="event"
											class="cursor-pointer"
											style="color: var(--q-primary)"
										>
										</q-icon>
									</template>
								</q-input>
							</template>
						</datepicker>
					</div>
					<div class="col-xs-12 col-sm-3 col-md-3">
						<datepicker
							menu-class-name="modalfix"
							v-model="dateAnnouncement"
							:locale="'th'"
							autoApply
							borderless
							range
							:enableTimePicker="false"
							week-start="0"
						>
							<template #year="{ year }">
								{{ year + 543 }}
							</template>
							<template #year-overlay-value="{ value }">
								{{ parseInt(value + 543) }}
							</template>
							<template #trigger>
								<q-input
									outlined
									dense
									class="full-width datepicker q-mb-md"
									:model-value="
										dateAnnouncement != null
											? dateThaiRange(dateAnnouncement)
											: null
									"
									:label="`${'วันที่ประกาศ'}`"
									:rules="[
										(val) =>
											!!val ||
											`${'กรุณาเลือกวันที่ประกาศ'}`,
									]"
								>
									<template v-slot:prepend>
										<q-icon
											name="event"
											class="cursor-pointer"
											style="color: var(--q-primary)"
										>
										</q-icon>
									</template>
								</q-input>
							</template>
						</datepicker>
					</div>
					<div
						class="col-xs-12 col-sm-3 col-md-3"
						v-if="announcementExam"
					>
						<datepicker
							menu-class-name="modalfix"
							v-model="dateRegister"
							:locale="'th'"
							autoApply
							borderless
							range
							:enableTimePicker="false"
							week-start="0"
						>
							<template #year="{ year }">
								{{ year + 543 }}
							</template>
							<template #year-overlay-value="{ value }">
								{{ parseInt(value + 543) }}
							</template>
							<template #trigger>
								<q-input
									outlined
									dense
									class="full-width datepicker q-mb-md"
									:model-value="
										dateRegister != null
											? dateThaiRange(dateRegister)
											: null
									"
									:label="`${'วันที่สมัคร'}`"
									:rules="[
										(val) =>
											!!val ||
											`${'กรุณาเลือกวันที่สมัคร'}`,
									]"
								>
									<template v-slot:prepend>
										<q-icon
											name="event"
											class="cursor-pointer"
											style="color: var(--q-primary)"
										>
										</q-icon>
									</template>
								</q-input>
							</template>
						</datepicker>
					</div>
					<div
						class="col-xs-12 col-sm-3 col-md-3"
						v-if="announcementExam"
					>
						<datepicker
							menu-class-name="modalfix"
							v-model="datePayment"
							:locale="'th'"
							autoApply
							borderless
							range
							:enableTimePicker="false"
							week-start="0"
						>
							<template #year="{ year }">
								{{ year + 543 }}
							</template>
							<template #year-overlay-value="{ value }">
								{{ parseInt(value + 543) }}
							</template>
							<template #trigger>
								<q-input
									outlined
									dense
									class="full-width datepicker q-mb-md"
									:model-value="
										datePayment != null
											? dateThaiRange(datePayment)
											: null
									"
									:label="`${'วันที่ชำระเงิน'}`"
									:rules="[
										(val) =>
											!!val ||
											`${'กรุณาเลือกวันที่ชำระเงิน'}`,
									]"
								>
									<template v-slot:prepend>
										<q-icon
											name="event"
											class="cursor-pointer"
											style="color: var(--q-primary)"
										>
										</q-icon>
									</template>
								</q-input>
							</template>
						</datepicker>
					</div>

					<div
						class="col-xs-12 col-sm-3 col-md-3"
						v-if="announcementExam"
					>
						<datepicker
							menu-class-name="modalfix"
							v-model="dateAnnounce"
							:locale="'th'"
							autoApply
							borderless
							:enableTimePicker="false"
							week-start="0"
						>
							<template #year="{ year }">
								{{ year + 543 }}
							</template>
							<template #year-overlay-value="{ value }">
								{{ parseInt(value + 543) }}
							</template>
							<template #trigger>
								<q-input
									outlined
									dense
									class="full-width datepicker q-mb-md"
									:model-value="
										dateAnnounce != null
											? date2Thai(dateAnnounce)
											: null
									"
									:label="`${'วันประกาศผลสอบ'}`"
									:rules="[
										(val) =>
											!!val ||
											`${'กรุณาเลือกวันประกาศผลสอบ'}`,
									]"
								>
									<template v-slot:prepend>
										<q-icon
											name="event"
											class="cursor-pointer"
											style="color: var(--q-primary)"
										>
										</q-icon>
									</template>
								</q-input>
							</template>
						</datepicker>
					</div>

					<div class="col-12">
						<q-separator size="5px" color="grey-2" />
					</div>

					<div class="row col-12 items-top q-col-gutter-x-sm">
						<div class="col-xs-12 col-sm-6">
							<div class="text-bold text-subtitle2 q-pb-sm">
								รูปภาพประกอบ
							</div>
							<div class="row justify-center row col-12">
								<q-uploader
									color="gray"
									type="file"
									flat
									ref="uploader"
									class="full-width"
									text-color="dark"
									:max-size="10000000"
									accept=".jpg,.png,.pdf,.csv,.doc"
									bordered
									label="[ไฟล์ jpg,png,pdf,csv,doc ขนาดไม่เกิน 10MB]"
									multiple
									@added="fileUploadImg"
									@removed="fileRemoveImg"
								>
									<template v-slot:header="scope">
										<div
											class="row no-wrap items-center q-pa-sm q-gutter-xs text-white"
										>
											<q-btn
												v-if="
													scope.queuedFiles.length > 0
												"
												icon="clear_all"
												@click="scope.removeQueuedFiles"
												round
												dense
												flat
											>
												<q-tooltip>ลบทั้งหมด</q-tooltip>
											</q-btn>
											<q-btn
												v-if="
													scope.uploadedFiles.length >
													0
												"
												icon="done_all"
												@click="
													scope.removeUploadedFiles
												"
												round
												dense
												flat
											>
												<q-tooltip
													>ลบไฟล์ที่อัปโหลด</q-tooltip
												>
											</q-btn>
											<q-spinner
												v-if="scope.isUploading"
												class="q-uploader__spinner"
											/>
											<div class="col">
												<div class="q-uploader__title">
													{{
														"[ไฟล์ jpg,png,pdf,csv,doc ขนาดไม่เกิน 10MB]"
													}}
												</div>
												<div
													class="q-uploader__subtitle"
												>
													{{ scope.uploadSizeLabel }}
													/
													{{
														scope.uploadProgressLabel
													}}
												</div>
											</div>
											<q-btn
												v-if="scope.canAddFiles"
												type="a"
												icon="add_box"
												@click="scope.pickFiles"
												round
												dense
												flat
											>
												<q-uploader-add-trigger />
												<q-tooltip>เลือกไฟล์</q-tooltip>
											</q-btn>
											<q-btn
												v-if="scope.isUploading"
												icon="clear"
												@click="scope.abort"
												round
												dense
												flat
											>
												<q-tooltip
													>ยกเลิกการอัปโหลด</q-tooltip
												>
											</q-btn>
										</div>
									</template>
								</q-uploader>
							</div>
							<q-card
								bordered
								flat
								class="full-width q-my-md"
								v-if="fileImgs.length != 0"
							>
								<q-list separator>
									<q-item
										v-for="file in fileImgs"
										:key="file.id"
										class="q-my-xs"
									>
										<q-item-section>
											<q-item-label
												class="full-width ellipsis"
											>
												{{ file.fileName }}
											</q-item-label>

											<q-item-label caption>
												สถานะ: {{ file.fileType }} /
												{{ file.fileSize }}
											</q-item-label>
										</q-item-section>
										<q-item-section top side>
											<div class="q-gutter-sm">
												<q-btn
													size="12px"
													flat
													dense
													round
													color="blue"
													icon="mdi-download-outline"
													@click="
														downloadData(
															file.detail
														)
													"
												>
													<q-tooltip
														>ดาวน์โหลด</q-tooltip
													>
												</q-btn>
												<q-btn
													size="12px"
													flat
													dense
													round
													color="red"
													icon="mdi-delete-outline"
													v-if="edit"
													@click="
														deleteImgData(file.id)
													"
												>
													<q-tooltip
														>ลบไฟล์</q-tooltip
													>
												</q-btn>
											</div>
										</q-item-section>
									</q-item>
								</q-list>
							</q-card>
						</div>
						<div class="col-xs-12 col-sm-6">
							<div class="text-bold text-subtitle2 q-pb-sm">
								เอกสารประกอบ
							</div>
							<div class="row justify-center row col-12">
								<q-uploader
									color="gray"
									type="file"
									flat
									ref="uploader"
									class="full-width"
									text-color="dark"
									:max-size="10000000"
									accept=".jpg,.png,.pdf,.csv,.doc"
									bordered
									label="[ไฟล์ jpg,png,pdf,csv,doc ขนาดไม่เกิน 10MB]"
									multiple
									@added="fileUploadDoc"
									@removed="fileRemoveDoc"
								>
									<template v-slot:header="scope">
										<div
											class="row no-wrap items-center q-pa-sm q-gutter-xs text-white"
										>
											<q-btn
												v-if="
													scope.queuedFiles.length > 0
												"
												icon="clear_all"
												@click="scope.removeQueuedFiles"
												round
												dense
												flat
											>
												<q-tooltip>ลบทั้งหมด</q-tooltip>
											</q-btn>
											<q-btn
												v-if="
													scope.uploadedFiles.length >
													0
												"
												icon="done_all"
												@click="
													scope.removeUploadedFiles
												"
												round
												dense
												flat
											>
												<q-tooltip
													>ลบไฟล์ที่อัปโหลด</q-tooltip
												>
											</q-btn>
											<q-spinner
												v-if="scope.isUploading"
												class="q-uploader__spinner"
											/>
											<div class="col">
												<div class="q-uploader__title">
													{{
														"[ไฟล์ jpg,png,pdf,csv,doc ขนาดไม่เกิน 10MB]"
													}}
												</div>
												<div
													class="q-uploader__subtitle"
												>
													{{ scope.uploadSizeLabel }}
													/
													{{
														scope.uploadProgressLabel
													}}
												</div>
											</div>
											<q-btn
												v-if="scope.canAddFiles"
												type="a"
												icon="add_box"
												@click="scope.pickFiles"
												round
												dense
												flat
											>
												<q-uploader-add-trigger />
												<q-tooltip>เลือกไฟล์</q-tooltip>
											</q-btn>
											<q-btn
												v-if="scope.isUploading"
												icon="clear"
												@click="scope.abort"
												round
												dense
												flat
											>
												<q-tooltip
													>ยกเลิกการอัปโหลด</q-tooltip
												>
											</q-btn>
										</div>
									</template>
								</q-uploader>
							</div>
							<q-card
								bordered
								flat
								class="full-width q-my-md"
								v-if="fileDocs.length != 0"
							>
								<q-list separator>
									<q-item
										v-for="file in fileDocs"
										:key="file.id"
										class="q-my-xs"
									>
										<q-item-section>
											<q-item-label
												class="full-width ellipsis"
											>
												{{ file.fileName }}
											</q-item-label>

											<q-item-label caption>
												สถานะ: {{ file.fileType }} /
												{{ file.fileSize }}
											</q-item-label>
										</q-item-section>
										<q-item-section top side>
											<div class="q-gutter-sm">
												<q-btn
													size="12px"
													flat
													dense
													round
													color="blue"
													icon="mdi-download-outline"
													@click="
														downloadData(
															file.detail
														)
													"
												>
													<q-tooltip
														>ดาวน์โหลด</q-tooltip
													>
												</q-btn>
												<q-btn
													size="12px"
													flat
													dense
													round
													color="red"
													icon="mdi-delete-outline"
													v-if="edit"
													@click="
														deleteDocData(file.id)
													"
												>
													<q-tooltip
														>ลบไฟล์</q-tooltip
													>
												</q-btn>
											</div>
										</q-item-section>
									</q-item>
								</q-list>
							</q-card>
						</div>
					</div>
					<div class="col-12">
						<q-separator
							size="5px"
							color="grey-2"
							class="q-my-lg"
						/>
					</div>

					<div class="col-12">
						<div class="text-bold text-subtitle2 q-pb-sm q-pt-md">
							รายละเอียด
						</div>
						<q-editor
							v-model="editor"
							:dense="$q.screen.lt.md"
							toolbar-text-color="blue-grey-10"
							toolbar-bg="blue-grey-2"
							toolbar-toggle-color="blue-grey-8"
							class="editor"
							:toolbar="[
								['left', 'center', 'right', 'justify'],
								[
									'bold',
									'italic',
									'strike',
									'underline',
									'subscript',
									'superscript',
								],
								['token', 'hr', 'link', 'custom_btn'],
								['print', 'fullscreen'],
								[
									{
										label: $q.lang.editor.formatting,
										icon: $q.iconSet.editor.formatting,
										list: 'no-icons',
										options: ['p', 'h1', 'h2', 'h3'],
									},
									{
										label: $q.lang.editor.defaultFont,
										icon: $q.iconSet.editor.font,
										fixedIcon: true,
										list: 'no-icons',
										options: [
											'default_font',
											'arial',
											'arial_black',
											'comic_sans',
											'courier_new',
											'impact',
											'lucida_grande',
											'times_new_roman',
											'verdana',
										],
									},
									'removeFormat',
								],
								['undo', 'redo'],
								['viewsource'],
							]"
							:fonts="{
								arial: 'Arial',
								arial_black: 'Arial Black',
								comic_sans: 'Comic Sans MS',
								courier_new: 'Courier New',
								impact: 'Impact',
								lucida_grande: 'Lucida Grande',
								times_new_roman: 'Times New Roman',
								verdana: 'Verdana',
							}"
						/>
					</div>
					<div class="col-12 q-mt-md">
						<q-input
							outlined
							v-model="note"
							label="หมายเหตุ"
							dense
							lazy-rules
							type="textarea"
						/>
					</div>
				</div>
			</q-card-section>
			<q-separator />
			<q-card-actions class="text-primary q-py-sm">
				<q-space />
				<q-btn
					flat
					round
					color="public"
					@click="checkSave"
					icon="mdi-content-save-outline"
				>
					<q-tooltip>{{
						edit ? "แก้ไขข้อมูล" : "บันทึกข้อมูล"
					}}</q-tooltip>
				</q-btn>
			</q-card-actions>
		</q-form>
	</q-card>
</template>
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { onMounted, ref, watch } from "vue";
import { useQuasar, QForm } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRouter, useRoute } from "vue-router";
import type { RequestPeriodCompete } from "@/modules/03_recruiting/interface/request/Period";
import type {
	DataOption,
	UploadType,
} from "@/modules/02_organizational/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";



const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();
const router = useRouter();
const route = useRoute();
const { date2Thai, success, dateToISO, notifyError, showLoader, hideLoader } = mixin;
const myForm = ref<QForm | null>(null); //form data input
const name = ref<string>("");
const note = ref<string>("");
const editor = ref<string>("");
const announcementExam = ref<boolean>(true);
const fee = ref<number>(0);
const round = ref<number>(1);
const yearly = ref<number>(new Date().getFullYear());
const dateRegister = ref<[Date, Date] | null>(null); //วันที่สมัคร
const datePayment = ref<[Date, Date] | null>(null); //วันที่จ่ายเงิน
const dateAnnouncement = ref<[Date, Date] | null>(null); //วันที่ประกาศ
const dateExam = ref<Date | null>(null); //วันที่สอบ
const dateAnnounce = ref<Date | null>(null); //วันที่ประกาศผล
const positionPathOptions = ref<DataOption[]>([]);
const organizationShortName = ref<DataOption>({ id: "", name: "" });
const organizationName = ref<DataOption>({ id: "", name: "" });
const organizationNameOptions = ref<DataOption[]>([]);
const { messageError } = mixin;
const fileDocDataUpload = ref<File[]>([]);
const fileDocs = ref<UploadType[]>([]);
const fileImgDataUpload = ref<File[]>([]);
const fileImgs = ref<UploadType[]>([]);
const id = ref<string>("");
const pay = ref<string>("");
const edit = ref<boolean>(false);
const columnsPayment = ref<QTableProps["columns"]>([
	{
		name: "accountNumber",
		align: "left",
		label: "เลขบัญชี",
		sortable: true,
		field: "accountNumber",
		headerStyle: "font-size: 14px",
		style: "font-size: 14px",
		sort: (a: string, b: string) =>
			a.localeCompare(b, undefined, {
				numeric: true,
				sensitivity: "base",
			}),
	},
	{
		name: "bankName",
		align: "left",
		label: "ธนาคาร",
		sortable: true,
		field: "bankName",
		headerStyle: "font-size: 14px",
		style: "font-size: 14px",
		sort: (a: string, b: string) =>
			a.localeCompare(b, undefined, {
				numeric: true,
				sensitivity: "base",
			}),
	},
	{
		name: "accountName",
		align: "left",
		label: "ชื่อบัญชี",
		sortable: true,
		field: "accountName",
		headerStyle: "font-size: 14px",
		style: "font-size: 14px",
		sort: (a: string, b: string) =>
			a.localeCompare(b, undefined, {
				numeric: true,
				sensitivity: "base",
			}),
	},
]);
const visibleColumnsPosition = ref<String[]>(["position", "type"]);
const columnsPosition = ref<QTableProps["columns"]>([
	{
		name: "position",
		align: "left",
		label: "ตำแหน่ง",
		sortable: true,
		field: "position",
		headerStyle: "font-size: 14px",
		style: "font-size: 14px",
		sort: (a: string, b: string) =>
			a.localeCompare(b, undefined, {
				numeric: true,
				sensitivity: "base",
			}),
	},
	{
		name: "type",
		align: "left",
		label: "ประเภทแบบฟอร์ม",
		sortable: true,
		field: "type",
		headerStyle: "font-size: 14px",
		style: "font-size: 14px",
		sort: (a: string, b: string) =>
			a.localeCompare(b, undefined, {
				numeric: true,
				sensitivity: "base",
			}),
	},
]);

watch(organizationShortName, (count: DataOption, prevCount: DataOption) => {
	organizationNameOptions.value = [];
});

watch(organizationName, (count: DataOption, prevCount: DataOption) => {
	positionPathOptions.value = [];
});

onMounted(async () => {
	hideLoader();
	if (route.params.id != undefined) {
		edit.value = true;
		id.value = route.params.id.toString();
		await fetchData();
	} else {
		edit.value = false;
	}
});

const clickBack = () => {
	router.push({ name: "competePeriod" });
};

const fetchData = async () => {
	showLoader();
	await http
		.get(config.API.getPeriodById(id.value))
		.then((res) => {
			const data = res.data.result.periods;
			const images = res.data.result.images;
			const files = res.data.result.files;

			id.value = data.id;
			name.value = data.name;
			round.value = data.order;
			yearly.value = data.year;
			fee.value = data.fee;
			dateAnnouncement.value =
				data.announcementStartDate != null &&
				data.announcementEndDate != null
					? [
							new Date(data.announcementStartDate),
							new Date(data.announcementEndDate),
					  ]
					: null;
			dateExam.value =
				data.examDate != null ? new Date(data.examDate) : null;
			dateRegister.value =
				data.registerStartDate != null && data.registerEndDate != null
					? [
							new Date(data.registerStartDate),
							new Date(data.registerEndDate),
					  ]
					: null;
			datePayment.value =
				data.paymentStartDate != null && data.paymentEndDate != null
					? [
							new Date(data.paymentStartDate),
							new Date(data.paymentEndDate),
					  ]
					: null;

			editor.value = data.detail;
			note.value = data.note;
			dateAnnounce.value =
				data.announcementDate != null
					? new Date(data.announcementDate)
					: null;

			fileDocs.value = files;
			fileImgs.value = images;
		})
		.catch((e) => {
			messageError($q, e);
		})
		.finally(() => {
			hideLoader();
		});
};

const fileUploadDoc = async (files: any) => {
	files.forEach((file: any) => {
		fileDocDataUpload.value.push(file);
	});
};

const fileRemoveDoc = async (files: any) => {
	files.forEach((file: any) => {
		const index = fileDocDataUpload.value.findIndex(
			(x: any) => x.__key == file.__key
		);
		if (index > -1) {
			fileDocDataUpload.value.splice(index, 1);
		}
	});
};

const uploadDocData = async () => {
	const formData = new FormData();
	if (fileDocDataUpload.value.length > 0) {
		fileDocDataUpload.value.forEach((file: any) => {
			formData.append("", file);
		});
		showLoader();
		await http
			.put(config.API.periodRecruitDoc(id.value), formData)
			.then((res) => {})
			.catch((e) => {
				messageError($q, e);
			})
			.finally(async () => {
				hideLoader();
				success($q, "บันทึกข้อมูลสำเร็จ");
				clickBack();
			});
	} else {
		success($q, "บันทึกข้อมูลสำเร็จ");
		clickBack();
	}
};

const uploadImgData = async () => {
	if (fileImgDataUpload.value.length > 0) {
		const formData = new FormData();
		fileImgDataUpload.value.forEach((file: any) => {
			formData.append("", file);
		});
		showLoader();
		await http
			.put(config.API.periodRecruitImg(id.value), formData)
			.then((res) => {})
			.catch((e) => {
				messageError($q, e);
			})
			.finally(async () => {
				hideLoader();
			});
	}
};

const fileUploadImg = async (files: any) => {
	files.forEach((file: any) => {
		fileImgDataUpload.value.push(file);
	});
};

const fileRemoveImg = async (files: any) => {
	files.forEach((file: any) => {
		const index = fileImgDataUpload.value.findIndex(
			(x: any) => x.__key == file.__key
		);
		if (index > -1) {
			fileImgDataUpload.value.splice(index, 1);
		}
	});
};

const downloadData = async (path: string) => {
	window.open(path);
};

const updateYear = async (e: number) => {
	yearly.value = e;
};

const checkSave = async () => {
	if (myForm.value !== null) {
		myForm.value.validate().then(async (success) => {
			if (success) {
				if (edit.value) {
					await editData(id.value);
				} else {
					await addData();
				}
			}
		});
	}
};

const sendData = () => {
	const valueData: RequestPeriodCompete = {
		announcementEndDate:
			dateAnnouncement.value !== null
				? dateToISO(dateAnnouncement.value[1])
				: null,
		announcementStartDate:
			dateAnnouncement.value !== null
				? dateToISO(dateAnnouncement.value[0])
				: null,
		examDate: dateExam.value !== null ? dateToISO(dateExam.value) : null,
		detail: editor.value,
		fee: fee.value,
		id: "",
		name: name.value,
		note: note.value,
		paymentEndDate:
			datePayment.value !== null ? dateToISO(datePayment.value[1]) : null,
		paymentStartDate:
			datePayment.value !== null ? dateToISO(datePayment.value[0]) : null,
		registerEndDate:
			dateRegister.value !== null
				? dateToISO(dateRegister.value[1])
				: null,
		registerStartDate:
			dateRegister.value !== null
				? dateToISO(dateRegister.value[0])
				: null,
		order: round.value,
		year: yearly.value,
		announcementDate:
			dateAnnounce.value !== null ? dateToISO(dateAnnounce.value) : null,
	};
	return valueData;
};

const deleteDocData = async (docId: string) => {
	showLoader();
	await http
		.delete(config.API.periodDeleteDoc(docId))
		.then(async () => {
			await fetchData();
		})
		.catch((e) => {
			messageError($q, e);
		})
		.finally(async () => {
			hideLoader();
		});
};

const deleteImgData = async (docId: string) => {
	showLoader();
	await http
		.delete(config.API.periodDeleteImg(docId))
		.then(async () => {
			await fetchData();
		})
		.catch((e) => {
			messageError($q, e);
		})
		.finally(async () => {
			hideLoader();
		});
};

const addData = async () => {
	showLoader();
	await http
		.post(config.API.savePeriod, sendData())
		.then(async (res) => {
			const data = res.data.result;
			id.value = data.id;
			await uploadImgData();
			await uploadDocData();
		})
		.catch((e) => {
			messageError($q, e);
		})
		.finally(async () => {
			hideLoader();
		});
};

const editData = async (id: string) => {
	showLoader();
	await http
		.put(config.API.editPeriod(id), sendData())
		.then(async () => {
			await uploadImgData();
			await uploadDocData();
		})
		.catch((e) => {
			messageError($q, e);
		})
		.finally(async () => {
			hideLoader();
		});
};

/**
 * แปลงช่วงวันที่ถ้า2ค่าเป็นวันเดียวกันจะโชววันเดียวแต่ถ้าไม่เท่ากันจะแสดงเป็นช่วง
 * @param val ช่วงวันที่
 */
const dateThaiRange = (val: [Date, Date]) => {
	if (val === null) {
		return "";
	} else if (date2Thai(val[0], true) === date2Thai(val[1], true)) {
		return `${date2Thai(val[0], true)}`;
	} else {
		return `${date2Thai(val[0], true)} - ${date2Thai(val[1], true)}`;
	}
};
</script>

<style></style>
