<template>
	<el-main>
		<x2-progress-track v-if="(booking.status == 'x2_cash' || booking.status == 'x2_cheque' || booking.status == 'x2_ba')"
		    v-model="trackerConfig" />
		<progress-track v-else v-model="trackerConfig" />
		<div align="center" v-if="booking.user_bankslip_path">
			<h4 style="margin-top:5%">
				Your Bankslip Has Been Rejected, Please Reupload Your Bankslip
				<br> Reason : {{ booking.reject_reason }}
			</h4>
			<br>
			<br>
		</div>
		<div v-else align="center">
			<h1>Please Upload Bankslip</h1>
		</div>

		<div class="row">
			<table class="table table-striped">
				<tbody>
					<tr>
						<td>Amount : </td>
						<td>
							<b>RMB {{ booking.amount }}</b>
						</td>
					</tr>
					<tr>
						<td>Bankin Amount : </td>
						<td>
							<b> MYR {{ booking.bankin_amount }}</b>
						</td>
					</tr>
					<tr>
						<td colspan="2">
							<b>{{ bankDetail.company_name }}</b>
							<br> {{ bankDetail.bank_name }} : {{ bankDetail.acc_no }}
						</td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="row timer">
			<div class="col">
				<vue-countdown :countdownend="handleCoutdownend" :time="booking.timeout">
					<template slot-scope="props">Time Remaining：
						<br>{{ props.days }} days, {{ props.hours }} hours, {{ props.minutes }} minutes, {{ props.seconds }} seconds.</template>
				</vue-countdown>
			</div>
		</div>
	<div style="position: relative;">
		<div v-show="isLoading" style=" position: absolute; height: 100%; width: 100%; background-color: rgba(255, 255,255,0.8); z-index: 99; " >
			<div class="row align-items-center justify-content-center" style="height: 100%;">
				<div class="col">
					<breeding-rhombus-spinner
						:animation-duration="1000"
						:size="60"
						:color="'#ff1d5e'" style="margin: auto; " />
						<p style="text-align:center; margin-top:30px; text-weight:bold;">Please wait, uploading bankslip...</p>
				</div>
			</div>
		</div>
	<!-- upload image -->
	<div class="row upload">
		<div class="col">
			<!-- <el-upload :action="'/api/booking/' + booking_id + '/upload-user-bankslip'" :show-file-list="false" :on-preview="handlePictureCardPreview"
				:on-remove="handleRemove" :on-error="uploadError" accept=".jpeg, .jpg, .png, .bmp, .doc, .docx, .xls, .xlsx, .pdf" list-type="picture-card"
				align="center">
				<i class="el-icon-plus" />
			</el-upload>
			<el-dialog :visible.sync="dialogVisible">
				<img :src="dialogImageUrl" width="100%" alt="">
			</el-dialog> -->
			<el-upload 
				class="avatar-uploader"
				ref="upload"
				action="'/api/booking/' + booking_id + '/upload-user-bankslip'"
				list-type="picture-card"
				:auto-upload="false"
				:show-file-list="true"
				:on-success="handleUploadSuccess" 
				:on-change="beforeFileUpload"
				:on-preview="handlePictureCardPreview"
  				:on-remove="handleRemove"
				algin="center">
				<i class="el-icon-plus"></i>
			</el-upload>
		</div>
	</div>	
	
	<!-- upload image end -->
	<div class="row bankinAmount">
		<div class="col">
			Bankin Amount (RM) :<br>
			<el-form ref="user_slip_form" :model="user_slip_form" :rules="rules">
				<el-form-item prop="transfer_amount">
					<el-input class="transferAmountInput" v-model="user_slip_form.transfer_amount" type="text" placeholder="Transfer Amount"/>
				</el-form-item>
				<el-form-item>
					<el-button :loading="loading" type="primary" :disabled="user_slip_form.transfer_amount == ''"  @click="submitUserSlip('user_slip_form')">Submit</el-button>
					<router-link :to="{ name: 'home' }" class="small ml-auto my-auto">
						Next Order
					</router-link>
				</el-form-item>	
			</el-form>
		</div>
	</div>
	</div>
	</el-main>
</template>
<style>
	h1 {
		margin-top: 5%;
		font-size: 3vw;
		text-align: center;
		margin-bottom: 3%;
	}

	.timer,
	.upload,
	.bankinAmount {
		text-align: center;
	}

	.transferAmountInput {
		width: 20%;
	}

	.row {
		margin-bottom: 3%;
	}

	td:last-child {
		text-align: center;
	}

	@media screen and (max-width: 767px) {
		.transferAmountInput {
			width: 60%;
		}
		.table {
			font-size: 3.5vmin;
		}
		h1 {
			font-size: 1em;
		}
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
<script>
	import VueCountdown from '@xkeshi/vue-countdown'
	import ProgressTrack from '~/components/ProgressTrack'
	import X2ProgressTrack from '~/components/X2ProgressTrack'
	import axios from 'axios'
	import ImageCompressor from 'image-compressor.js';
	import { BreedingRhombusSpinner } from 'epic-spinners';

	export default {
		middleware: ['auth'],
		name: 'MyComponent',
		components: {
			'vue-countdown': VueCountdown,
			'progress-track': ProgressTrack,
			'x2-progress-track': X2ProgressTrack,
			BreedingRhombusSpinner
		},
		data() {
			return {
				trackerConfig: {
					status: 2,
					term: null
				},
				start: false,
				loading: false,
				isLoading: false,
				dialogImageUrl: '',
				imageUrl: null,
				dialogVisible: false,
				booking_id: this.$route.params.id,
				user_slip_form: {
					transfer_amount: '',
					slip_image: ''
				},
				booking: {
					amount: '',
					bankin_amount: '',
					timeout: 1,
					term: '123',
					user_bankslip_path: null,
					reject_reason: null,
				},
				rules: {
					transfer_amount: [{
						required: true,
						message: 'Please input amount',
						trigger: 'change'
					}]
				},
				active_bank_setting: {
					x1_bank_id: null,
					x2_bank_id: null,
					beneficiary_id: null
				},
				bankDetail: {},
			}
		},
		beforeCreate() {
			const loading = this.$loading({
				lock: true,
				text: 'Please wait..',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})

			axios.get('/api/booking/' + this.$route.params.id)
				.then((response) => {
					this.booking.amount = response.data.amount;
					this.booking.bankin_amount = response.data.bia;
					this.booking.timeout = response.data.timeout * 1000;
					this.booking.term = response.data.term;
					this.booking.status = response.data.status;					
					this.trackerConfig.term = response.data.term

					if (response.data.user_bankslip_path) {
						this.booking.user_bankslip_path = response.data.user_bankslip_path
						this.booking.reject_reason = response.data.reject_reason
					}
					console.log(this.booking);
					this.start = true;

					if (this.booking.timeout < 0) {
						this.$message({
							showClose: true,
							message: 'Booking timeout, please make another booking.',
							type: 'error',
							duration: 30000
						})
						this.$router.push({
							name: 'home'
						})
					}
				}).then(() => {
                axios.get('/api/active-bank')
                    .then((response) => {
                        this.active_bank_setting = response.data;
                        var url = '';
                        if (this.booking.term === 'x1_cash' || this.booking.term === 'x1_cheque' || this.booking.term === 'x1_ba') {
                            url = '/api/malaysia-bank/' + this.active_bank_setting.x1_bank_id;
                        } else if (this.booking.term === 'x2_cash' || this.booking.term === 'x2_cheque' || this.booking.term === 'x2_ba') {
                            url = '/api/malaysia-bank/' + this.active_bank_setting.x2_bank_id;
                        }

                        axios.get(url)
                            .then((response) => {
                                this.bankDetail = response.data;
                                loading.close()
                            })
                            .catch((error) => {
                                loading.close()
                                console.log(error);
                                this.$message({
                                    showClose: true,
                                    message: 'Fetch data fail',
                                    type: 'error',
                                    duration: 10000
                                });
                            });
                    })
                    .catch((error) => {
                        console.log(error);
                        this.$message({
                            showClose: true,
                            message: 'Fetch bank details fail',
                            type: 'error',
                            duration: 10000
                        });
                    });
			}).catch((error) => {
					this.$router.push({
						name: 'notfound'
					})
					console.log(error)
				});
		},
		methods: {
			handleUploadSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
				this.$message({
					showClose: true,
					message: 'Uploaded.',
					type: 'success',
					duration: 5000
				})
			},

			beforeFileUpload(file) {
				this.isLoading = true;
				//const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;
				var vm = this;
				var filetype = file.raw.type.split("/")[0];
				if(filetype === 'image'){
					new ImageCompressor(file.raw, {
					quality: .4,
					convertSize: 1500000,
					success(result) {
						vm.convertFile(result)
					},
					error(e) {
						console.log(e.message);
					}
					});
				} else {
					this.convertFile(file.raw)
				}

				this.$message({
					showClose: true,
					message: 'Uploading..',
					type: 'success',
					duration: 5000
				})
				// return isJPG && isLt2M;
				return isLt2M;
			},
			convertFile(file){
				var vm = this,
					reader = new FileReader();
				reader.readAsDataURL(file); 
				reader.onloadend = function() {
					vm.isLoading = false;
					vm.imageUrl = reader.result;
					vm.user_slip_form.slip_image = reader.result;
				}
			},
			handleCoutdownend() {
				this.$message({
					showClose: true,
					message: 'Booking timeout, please make another booking.',
					type: 'error',
					duration: 30000
				})
				this.$router.push({
					name: 'home'
				})
			},
			handleRemove(file, fileList) {
				// console.log(file, fileList)
			},
			uploadError(file, fileList) {
				this.$message.warning(`Incorrect file format or file size too big.`)
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url
				this.dialogVisible = true
			},
			submitUserSlip(formName) {
				this.loading = true
				if (this.booking.amount == '') {
					this.$message({
						showClose: true,
						message: 'Please key in your bankin amount first.',
						type: 'warning',
						duration: 10000
						
					})
					return;
				}
				this.$refs[formName].validate((valid) => {
					if (valid) {
						let newConfirmation = {
							amount: this.booking.amount,
							term: this.term
						}
					} else {
						this.loading = false
					}
				})
				let newUserSlip = {
					transfer_amount: this.user_slip_form.transfer_amount
				}
				axios.patch('/api/booking/' + this.booking_id + '/bankslip-amount/', this.user_slip_form)
					.then((response) => {
						console.log(response);

						this.$message({
							showClose: true,
							message: 'Your bankinslip has been submitted, please wait admin to approve.',
							type: 'success',
							duration: 5000
						})

						this.$router.push({
							name: 'home'
						})
                    
					}).catch((error) => {
						this.$message({
							showClose: true,
							message: 'Please upload your bankin slip first.',
							type: 'warning',
							duration: 10000
							
						})
						

						this.loading = false
						console.log(error)
					}) 

			},
		
			handleTimeExpire() {
				alert('Booking expired')
			},
			startTimer() {
				this.start = true;
			}
		}
	}
</script>