<template>
	<view class="page-container">
		<scroll-view style="height: 100%" scroll-y="true">
			<view class="scroll-container">
				<canvas canvas-id="canvas" id="canvas" @longtap="saveImage" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" @click="toLogin"></canvas>
				<view v-if="isLogin" class="share-bottom">
					<view class="flex-row">
						<view class="share-bottom-button" @click="saveImage">保存二维码</view>
						<view class="share-bottom-button2" @click="openShare">推荐好友注册</view>
					</view>
					<view class="share-way flex-row">
						<navigator url="/pages/user/share-way" hover-class="none">
							<image src="/static/icon/gesture.png" mode="widthFix" />
							<text>推广太难？点这里</text>
						</navigator>
					</view>
				</view>
			</view>
		</scroll-view>
		<share ref="share" :url="shareUrl"></share>
	</view>
</template>

<script>
import html2canvas from 'html2canvas';
import share from '@/components/share';
import { baseURL } from '@/utils/request';

export default {
	components: {
		share
	},
	data() {
		return {
			isLogin: false,
			shareBg: '/static/images/share-bg.png',
			shareUrl: '',
			qrcodeImg: baseURL() + '/api/user/qrcode',
			qrcode: '',
			drawComplete: false,
			qrcodeSize: 0,
			canvasWidth: 0,
			canvasHeight: 0
		};
	},
	watch: {
		qrcode: {
			handler(val) {
				this.drawComplete = false;
			}
		}
	},
	async onShow() {
		await this.$onLaunched;
		const token = getApp().globalData.userToken;
		this.isLogin = token ? true : false;
		this.qrcode = getApp().globalData.share.code;
		this.shareUrl = getApp().globalData.share.url;
		if (this.qrcode) {
			this.shareUrl += (this.shareUrl.indexOf('?') !== -1 ? '&code=' : '?code=') + this.qrcode;
		}
		this.$nextTick(() => {
			if (this.drawComplete === false) {
				this.generatePoster();
				uni.onWindowResize((res) => {
					this.generatePoster();
				});
			}
		});
	},
	methods: {
		generatePoster: async function () {
			const bgInfo = await this.getImageInfo(this.shareBg).then((res) => res);
			this.canvasWidth = uni.getSystemInfoSync().windowWidth;
			this.canvasHeight = (this.canvasWidth / bgInfo.width) * bgInfo.height;
			this.qrcodeSize = this.canvasWidth * 0.6;
			this.$nextTick(() => {
				const canvas = uni.createCanvasContext('canvas', this);
				canvas.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				canvas.drawImage(this.shareBg, 0, 0, this.canvasWidth, this.canvasHeight);
				canvas.drawImage(
					this.qrcodeImg + (this.qrcode && '?code=' + this.qrcode),
					(this.canvasWidth - this.qrcodeSize) / 2,
					this.canvasHeight * 0.35,
					this.qrcodeSize,
					this.qrcodeSize
				);
				if (this.isLogin && this.qrcode) {
					this.drawCode(canvas, this.qrcode);
				} else {
					canvas.setFillStyle('rgba(255, 255, 255, 0.8)');
					canvas.fillRect(this.canvasWidth * 0.18, this.canvasHeight * 0.355, this.canvasWidth * 0.64, this.canvasHeight * 0.357);
					canvas.setFillStyle('#333333');
					canvas.setFontSize(this.canvasWidth * 0.05);
					const textWidth = canvas.measureText('请先登录').width;
					canvas.fillText('请先登录', (this.canvasWidth - textWidth) / 2, this.canvasHeight * 0.516 + this.qrcodeSize);
				}
				setTimeout(() => {
					canvas.draw();
				}, 100);
				this.drawComplete = true;
			});
		},
		drawCode: function (canvas, text) {
			canvas.setFillStyle('#ec5834');
			canvas.setFontSize(this.canvasWidth * 0.06);
			const textWidth = canvas.measureText(text).width;
			canvas.fillText(text, (this.canvasWidth - textWidth) / 2, this.canvasHeight * 0.519 + this.qrcodeSize);
		},
		getImageInfo: function (url) {
			return new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: url,
					success: function (image) {
						resolve(image);
					}
				});
			});
		},
		saveImage: function () {
			return new Promise((resolve, reject) => {
				uni.showLoading({
					title: '正在保存'
				});
				// #ifdef H5
				const canvasId = document.querySelector('#canvas');
				html2canvas(canvasId, {
					useCORS: false
				}).then((canvas) => {
					canvas.toBlob((res) => {
						const a = document.createElement('a');
						a.download = 'share.png';
						a.href = URL.createObjectURL(res);
						document.body.appendChild(a);
						a.click();
						URL.revokeObjectURL(res);
						document.body.removeChild(a);
						resolve(a.href);
						uni.hideLoading();
					}, 'image/png');
				});
				// #endif
				// #ifndef H5
				uni.canvasToTempFilePath({
					canvasId: 'canvas',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									icon: 'none',
									title: '图片保存成功~!',
									duration: 3000
								});
								resolve(true);
							},
							fail: function (e) {
								resolve(false);
							}
						});
					},
					fail: function (err) {
						resolve(false);
					}
				});
				// #endif
			}).then((res) => {
				if (res === false) {
					uni.showToast({
						icon: 'none',
						title: '保存图片失败~!',
						duration: 3000
					});
				}
			});
		},
		openShare() {
			this.$refs.share.showSharePopup = true;
		},
		toLogin() {
			if (this.isLogin === false) {
				uni.navigateTo({
					url: '/pages/user/login'
				});
			}
		}
	}
};
</script>

<style lang="scss">
.page-container {
	height: 100%;
	background-color: #da2538;

	.share-bottom {
		padding: 0 3% 20px;

		.share-bottom-button {
			flex: 1 1 0%;
			margin: 0 2.8%;
			padding: 12px 5px;
			color: #ff4959;
			font-size: 16px;
			text-align: center;
			background: #ffffff;
			border-radius: 24px;
		}

		.share-bottom-button2 {
			flex: 1 1 0%;
			margin: 0 2.8%;
			padding: 12px 5px;
			color: #fff;
			font-size: 16px;
			text-align: center;

			background: #000000;
			border-radius: 24px;
		}

		.share-way {
			margin-top: 10px;
			padding: 10px 0;
			font-size: 14px;
			font-weight: 400;
			color: #252346;
			align-items: center;
			justify-content: center;

			uni-image {
				width: 24px;
				margin-right: 5px;
			}
		}
	}
}
</style>
