<template>
	<div class="panel panel-default nominee-add-page">
		<div class="panel-body">
			<div class="nominee-add-page__header clearfix">
				<h4 class="pull-left nominee-add-page__title">
					<i class="fa fa-pencil text-muted"></i> Kemaskini Calon
				</h4>
				<router-link :to="backToList" class="btn btn-default pull-right">
					<i class="fa fa-arrow-left"></i> Kembali
				</router-link>
			</div>

			<p class="text-muted small nominee-add-page__intro">
				Kemas kini maklumat calon. Medan bertanda <span class="text-danger">*</span> adalah wajib.
			</p>

			<form
				class="nominee-add-form"
				method="POST"
				id="edit_form"
				:action="data.API + 'nominee/' + id"
				enctype="multipart/form-data"
				@submit.prevent="edit()"
			>
				<input type="hidden" name="_method" value="PUT" />

				<div class="row">
					<div class="col-md-8">
						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label for="edit-nominee-name">Nama Calon <span class="text-danger">*</span></label>
									<input
										id="edit-nominee-name"
										v-model="form.name"
										type="text"
										name="name"
										class="form-control"
										placeholder="Nama penuh"
										required
									/>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label for="edit-nominee-no-anggota">No. Anggota <span class="text-danger">*</span></label>
									<input
										id="edit-nominee-no-anggota"
										v-model="form.no_anggota"
										type="text"
										name="no_anggota"
										class="form-control"
										placeholder="No. keahlian"
										required
									/>
								</div>
							</div>
						</div>

						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label for="edit-nominee-unit">Unit <span class="text-danger">*</span></label>
									<input
										id="edit-nominee-unit"
										v-model="form.unit"
										type="text"
										name="unit"
										class="form-control"
										required
									/>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label for="edit-nominee-umur">Umur <span class="text-danger">*</span></label>
									<input
										id="edit-nominee-umur"
										v-model="form.umur"
										type="number"
										name="umur"
										class="form-control"
										min="1"
										max="120"
										placeholder="Tahun"
										required
									/>
								</div>
							</div>
						</div>

						<div class="form-group">
							<label for="edit-nominee-jawatan-sekarang">Jawatan Sekarang <span class="text-danger">*</span></label>
							<input
								id="edit-nominee-jawatan-sekarang"
								v-model="form.jawatan_sekarang"
								type="text"
								name="jawatan_sekarang"
								class="form-control"
								required
							/>
						</div>

						<div class="form-group">
							<label for="edit-nominee-education">Taraf Pendidikan</label>
							<input
								id="edit-nominee-education"
								v-model="form.education"
								type="text"
								name="education"
								class="form-control"
								placeholder="Pilihan"
							/>
						</div>

						<div class="form-group">
							<label for="edit-nominee-experience">Pengalaman Kerja</label>
							<textarea
								id="edit-nominee-experience"
								v-model="form.experience"
								name="experience"
								class="form-control"
								rows="4"
								placeholder="Pilihan — senaraikan pengalaman relevan"
							></textarea>
						</div>

						<div class="form-group">
							<label for="edit-nominee-position-id">Jawatan Dicalonkan <span class="text-danger">*</span></label>
							<select
								id="edit-nominee-position-id"
								v-model="form.position_id"
								class="form-control"
								name="position_id"
								required
							>
								<option value="" disabled>— Pilih jawatan —</option>
								<option
									v-for="position in data.positions"
									:key="position.id"
									:value="String(position.id)"
								>
									{{ position.name }}
								</option>
							</select>
						</div>

						<div class="form-group">
							<label for="edit-nominee-partylist-id">Senarai parti</label>
							<select
								id="edit-nominee-partylist-id"
								v-model="form.partylist_id"
								class="form-control"
								name="partylist_id"
							>
								<option value="">— Pilihan —</option>
								<option
									v-for="partylist in data.partylists"
									:key="partylist.id"
									:value="String(partylist.id)"
								>
									{{ partylist.name }}
								</option>
							</select>
						</div>
					</div>

					<div class="col-md-4">
						<div class="nominee-add-photo panel panel-default">
							<div class="panel-heading">
								<strong><i class="fa fa-camera"></i> Gambar calon</strong>
								<span class="text-muted small nominee-add-photo__hint">Pilihan</span>
							</div>
							<div class="panel-body">
								<div
									class="nominee-add-photo__preview"
									:class="{ 'nominee-add-photo__preview--empty': !imageUrl }"
								>
									<img v-if="imageUrl" :src="imageUrl" alt="Pratonton gambar calon" />
									<div v-else class="nominee-add-photo__placeholder">
										<i class="fa fa-picture-o"></i>
										<span>Tiada gambar</span>
									</div>
								</div>
								<label class="btn btn-default btn-block nominee-add-photo__browse" for="edit-nominee-file-input">
									<i class="fa fa-folder-open"></i> Pilih fail
								</label>
								<input
									id="edit-nominee-file-input"
									name="photo"
									type="file"
									class="nominee-add-photo__input"
									accept="image/*"
									@change="handleImageChange"
								/>
								<p class="text-muted small nominee-add-photo__formats">PNG, JPG atau GIF</p>
							</div>
						</div>
					</div>
				</div>

				<hr class="nominee-add-form__rule" />

				<div class="clearfix nominee-add-form__actions">
					<router-link :to="backToList" class="btn btn-default">
						<i class="fa fa-times"></i> Batal
					</router-link>
					<button type="submit" class="btn btn-primary" :disabled="loading">
						<i v-if="loading" class="fa fa-spinner fa-spin"></i>
						<i v-else class="fa fa-check"></i>
						{{ loading ? 'Menghantar…' : 'Simpan perubahan' }}
					</button>
				</div>
			</form>
		</div>
	</div>
</template>

<script>
export default {
	data: function () {
		return {
			imageUrl: '',
			loading: false,
			form: {
				name: '',
				no_anggota: '',
				unit: '',
				umur: '',
				jawatan_sekarang: '',
				education: '',
				experience: '',
				position_id: '',
				partylist_id: ''
			}
		}
	},

	created: function () {
		if (!this.nominee.id) this.$router.push({ name: 'Maklumat Calon' })
	},

	watch: {
		nominee: {
			immediate: true,
			deep: true,
			handler: function (n) {
				if (!n || !n.id) return
				this.form.name = n.name || ''
				this.form.no_anggota = n.no_anggota || ''
				this.form.unit = n.unit || ''
				this.form.umur = n.umur != null && n.umur !== '' ? String(n.umur) : ''
				this.form.jawatan_sekarang = n.jawatan_sekarang || ''
				this.form.education = this.formatEducationForInput(n.education)
				this.form.experience = this.formatExperienceForInput(n.experience)
				this.form.position_id = n.position_id != null ? String(n.position_id) : ''
				this.form.partylist_id =
					n.partylist_id != null && n.partylist_id !== '' ? String(n.partylist_id) : ''
				this.imageUrl = n.photo ? this.createBase64ImageUrl(n.photo) : ''
			}
		}
	},

	methods: {
		createBase64ImageUrl: function (base64ImageData) {
			return 'data:image/png;base64,' + base64ImageData
		},

		formatEducationForInput: function (val) {
			if (val == null || val === '') return ''
			if (Array.isArray(val)) return val.join('\n')
			return String(val)
		},

		formatExperienceForInput: function (val) {
			if (val == null || val === '') return ''
			if (Array.isArray(val)) {
				return val.map(function (x, i) {
					return i + 1 + '. ' + x
				}).join('\n')
			}
			return String(val)
		},

		handleImageChange: function (event) {
			var file = event.target.files[0]
			var imageType = /image.*/
			var vm = this

			if (file && file.type.match(imageType)) {
				var reader = new FileReader()
				reader.onload = function (e) {
					vm.imageUrl = e.target.result
				}
				reader.readAsDataURL(file)
			} else {
				event.target.value = ''
				vm.imageUrl = vm.nominee.photo ? vm.createBase64ImageUrl(vm.nominee.photo) : ''
			}
		},

		edit: function () {
			if (this.loading) return
			var vm = this
			this.loading = true
			this.util.notify('Kemaskini calon', 'progress', 0)
			$('#edit_form').ajaxSubmit({
				success: function (response) {
					$.notifyClose()
					vm.loading = false
					if (vm.util.showResult(response, 'success', 'ajax'))
						vm.$router.push({ name: 'Maklumat Calon', query: { refresh: true } })
				},
				error: function (error) {
					$.notifyClose()
					vm.loading = false
					vm.util.showResult(error, 'error', 'ajax')
				},
				uploadProgress: function (a, b, c, progress) {
					vm.util.notify('Kemaskini calon', 'progress', progress)
				}
			})
		}
	},

	computed: {
		id: function () {
			return this.$route.params.id
		},

		nominee: function () {
			for (var i in this.data.nominees)
				if (this.data.nominees[i].id == this.id) return this.data.nominees[i]
			return {}
		},

		backToList: function () {
			var q = {}
			if (this.nominee && this.nominee.position_id != null && String(this.nominee.position_id) !== '0') {
				q.position_id = this.nominee.position_id
			}
			return { name: 'Maklumat Calon', query: q }
		}
	}
}
</script>

<style scoped>
.nominee-add-page__header {
	margin-bottom: 12px;
	padding-bottom: 10px;
	border-bottom: 1px solid #eee;
}

.nominee-add-page__title {
	margin-top: 0;
	margin-bottom: 0;
	font-weight: 600;
}

.nominee-add-page__title .fa {
	margin-right: 6px;
}

.nominee-add-page__intro {
	margin-bottom: 18px;
}

.nominee-add-photo .panel-heading {
	display: flex;
	align-items: baseline;
	justify-content: space-between;
	gap: 8px;
}

.nominee-add-photo__hint {
	font-weight: normal;
}

.nominee-add-photo__preview {
	width: 100%;
	aspect-ratio: 1;
	max-height: 240px;
	border-radius: 4px;
	overflow: hidden;
	background: #f9f9f9;
	border: 1px dashed #ccc;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 12px;
}

.nominee-add-photo__preview--empty {
	min-height: 180px;
}

.nominee-add-photo__preview img {
	width: 100%;
	height: 100%;
	object-fit: cover;
	display: block;
}

.nominee-add-photo__placeholder {
	text-align: center;
	color: #999;
	padding: 16px;
}

.nominee-add-photo__placeholder .fa {
	font-size: 36px;
	display: block;
	margin-bottom: 8px;
	opacity: 0.65;
}

.nominee-add-photo__placeholder span {
	display: block;
	font-size: 12px;
}

.nominee-add-photo__input {
	position: absolute;
	width: 0.1px;
	height: 0.1px;
	opacity: 0;
	overflow: hidden;
	z-index: -1;
}

.nominee-add-photo__browse {
	margin-bottom: 0;
}

.nominee-add-photo__formats {
	margin: 8px 0 0;
	text-align: center;
}

.nominee-add-form__rule {
	margin-top: 8px;
	margin-bottom: 16px;
	border-top-color: #eee;
}

.nominee-add-form__actions {
	text-align: right;
}

.nominee-add-form__actions .btn + .btn {
	margin-left: 8px;
}

@media (max-width: 991px) {
	.nominee-add-photo {
		margin-top: 8px;
	}
}
</style>
