<template>
	<view v-if="show">		
		<uni-popup ref="customModalRef" :isMaskClick="options.isMaskClick" :mask-background-color="options.type === 'message' ? 'transparent' : ''">
			<view :class="['customModal', options.type === 'confirm' ? 'confirmModal' : 'messageModal']">
				<image src="/static/closeIcon.svg" mode="aspectFit" class="customModalCloseIcon" @click="onClose"></image>
				<view class="customModalDecoration">
					<view class="customModalDecorationLeft"></view>
					<view class="customModalDecorationRight"></view>
				</view>
				<view class="customModalContent">
					<view class="customModalContentStatusIcon" v-if="options.type === 'message'">
						<image v-if="options.status === 'success'" src="/static/success.png" mode="aspectFit" style="width: 35px; height: 35px"></image>
						<image v-if="options.status === 'warning'" src="/static/warning.png" mode="aspectFit" style="width: 35px; height: 35px"></image>
					</view>
					<view class="customModalContentText">
						<text>{{ options.contentText }}</text>
					</view>
				</view>
				<view class="customModalConfirmBtns" v-if="options.type === 'confirm'">
					<button class="secondaryButton cancelBtn" @click="onCancel">{{ options.cancelText }}</button>
					<view :disabled="confirmBtnLoading" class="primaryButton confirmBtn" @click="onConfirm">
						<image v-show="confirmBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
						{{ options.confirmText }}
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
export default {
	name: 'CustomModal',
	data() {
		return {
			options: {
				type: 'confirm',
				isMaskClick: false,
				closeAfterConfirm: true,
				confirmText: this.$t('common.okText'),
				cancelText: this.$t('common.cancelText')
			},
			confirmBtnLoading: false,
			show: false
		};
	},
	methods: {
		showDialog(options) {
			this.show = true
			this.options = { ...this.options, ...options };
			this.$nextTick(() => {
				this.$refs.customModalRef.open();
			})
		},
		async onConfirm() {
			try {
				if (this.options.onConfirm) {
					this.confirmBtnLoading = true;
					await this.options.onConfirm();
					this.confirmBtnLoading = false;
				}
			} catch (e) {
				console.log('e==>', e);
			}
			if (this.options.closeAfterConfirm) {
				this.closeDialog();
			}
		},
		async onCancel() {
			try {
				if (this.options.onCancel) {
					await this.options.onCancel();
				}
			} catch (e) {
				console.log('e==>', e);
			}
			await this.onClose();
			this.closeDialog();
		},
		async onClose() {
			try {
				if (this.options.onClose) {
					await this.options.onClose();
				}
			} catch (e) {
				console.log('e==>', e);
			}
			this.closeDialog();
		},
		closeDialog() {
			this.$refs.customModalRef.close();
			this.$nextTick(() => {
				this.show = false
			})
		}
	}
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
