<script setup lang="ts">
import { ref, onMounted } from "vue"
import { useQuasar } from "quasar"
import { useRouter, useRoute } from "vue-router"
import { useCounterMixin } from "@/stores/mixin"
import http from "@/plugins/http"
import config from "@/app.config"
import type { QForm } from "quasar"

const router = useRouter()
const $q = useQuasar()
const mixin = useCounterMixin()
const myform = ref<QForm | null>(null)
const { fails, success, messageError, showLoader, hideLoader } = mixin
const fileDocDataUpload = ref<File[]>([])
const route = useRoute()
const files = ref<any>()
const tranferOrg = ref("")
const noteReason = ref("")
const id = ref<string>("")
const nameFile = ref<string>("")

const routeName = router.currentRoute.value.name

onMounted(() => {
	if (route.params.id !== undefined) {
		id.value = route.params.id.toString()
		fecthDataTransfer(id.value)
	}
})

const filesNull = () => {
	files.value = null
}

const saveData = async () => {
	if (myform.value != null) {
		await myform.value.validate().then(async (saveDataTest: Boolean) => {
			if (saveDataTest) {
				saveTransfer()
			}
		})
	}
}

//บันทึกข้อมูลการโอน
const saveTransfer = () => {
	$q.dialog({
		title: "ยืนยันการยื่นข้อมูลการโอน",
		message: "ต้องการยื่นข้อมูลการโอนนี้ใช่หรือไม่?",
		cancel: {
			flat: true,
			color: "negative",
		},
		persistent: true,
	})
		.onOk(async () => {
			if (files.value == undefined) {
				fails($q, "กรุณากรอกอัพโหลดเอกสารเพิ่มเติม")
			} else {
				createTransfer()
			}
		})
		.onCancel(() => {})
		.onDismiss(() => {})
}

const createTransfer = async () => {
	const formData = new FormData()

	const blob = files.value.slice(0, files.value[0].size)
	const newFile = new File(blob, nameFile.value, {
		type: files.value[0].type,
	})
	formData.append("Organization", tranferOrg.value)
	formData.append("Reason", noteReason.value)
	formData.append("file", newFile)
	await http
		.post(config.API.listtransfer(), formData)
		.then((res: any) => {
			success($q, "บันทึกข้อมูลสำเร็จ")
			router.push(`/transfer`)
		})
		.catch((e: any) => {
			messageError($q, e)
		})
}

const fecthDataTransfer = async (id: string) => {
	showLoader()
	await http
		.get(config.API.transferByid(id))
		.then((res: any) => {
			let data = res.data.result
			tranferOrg.value = data.organization
			noteReason.value = data.reason
			files.value = data.docs
		})
		.catch((e: any) => {
			messageError($q, e)
		})
		.finally(() => {
			hideLoader()
		})
}

const fileUploadDoc = async (file: any) => {
	fileDocDataUpload.value.push(file)
	nameFile.value = file[0].name
	files.value = file
}
</script>

<template>
	<div class="col-12 row justify-center">
		<div class="col-xs-12 col-sm-12 col-md-11">
			<div class="toptitle text-white col-12 row items-center">
				<q-btn icon="mdi-arrow-left" unelevated round dense flat color="primary" class="q-mr-sm" @click="router.go(-1)" />
				<div v-if="routeName == 'addTransfer'">เพิ่มเรื่องขอโอน</div>
				<div v-else>รายละเอียดเรื่องขอโอน</div>
			</div>
			<q-form ref="myform" class="col-12">
				<q-card bordered>
					<div class="col-12 row q-col-gutter-md q-pa-md">
						<div class="col-xs-12 col-sm-12">
							<div class="col-12 row q-pa-sm q-col-gutter-sm">
								<q-input
									class="col-12"
									dense
									outlined
									v-model="tranferOrg"
									label="หน่วยงานที่ขอโอนไป"
									:readonly="routeName != 'addTransfer'"
									:rules="[(val:string) => !!val || `${'กรุณากรอกหน่วยงานที่ขอโอนไป'}`]"
								/>
								<q-input
									class="col-12"
									dense
									outlined
									v-model="noteReason"
									label="เหตุผล"
									type="textarea"
									:readonly="routeName != 'addTransfer'"
									:rules="[(val:string) => !!val || `${'กรุณากรอกเหตุผล'}`]"
								/>
								<div class="col-12 row" v-if="routeName == 'addTransfer'">
									<q-uploader
										bordered
										flat
										class="col-12"
										accept=".jpg,.png,.pdf,.csv,.doc"
										url="http://localhost:4444/upload"
										label="เอกสารเพิ่มเติม"
										type="file"
										@added="fileUploadDoc"
										@removed="filesNull"
									/>
								</div>
								<div class="col-12 row" v-if="routeName != 'addTransfer'">
									<div class="bg-grey-1 q-pa-sm col-12 row items-center text-primary">
										<div class="q-pl-sm text-weight-bold text-dark">เอกสารเพิ่มเติม</div>
									</div>
									<q-card bordered flat class="full-width">
										<q-list separator>
											<q-item v-for="file in files" :key="file.key" class="q-my-xs">
												<q-item-section>
													<q-item-label class="full-width ellipsis">
														{{ file.fileName }}
													</q-item-label>

													<q-item-label caption> </q-item-label>
												</q-item-section>
											</q-item>
										</q-list>
									</q-card>
								</div>
							</div>
						</div>
					</div>
					<q-separator v-if="routeName == 'addTransfer'" />
					<div class="row col-12 q-pa-md" v-if="routeName == 'addTransfer'">
						<q-space />
						<q-btn unelevated dense class="q-px-md items-center" color="primary" label="ยื่นเรื่องขอโอน" @click="saveData" />
					</div>
				</q-card>
			</q-form>
		</div>
	</div>
</template>
