<template>
	<view class="wrap safe-area" :style="[getStyle]">
		<view class="btn share-btn" @click="handleShare">
			<image :src="getFileUrl('home/share-icon.png')" mode="aspectFill"></image>
		</view>
	</view>
</template>

<script setup>
	import { computed, nextTick, ref, unref } from 'vue';
	import { getFileUrl } from '@/utils/file.js';
	import { getCurrentPageUrlWithArgs } from '@/utils/request.js'
	import { SHARE_ID, objectTOString, useShare } from './hook.js'
	import { SharePosterGetShareQrcode } from "@/api"
	import { omit } from 'lodash-es';
	
	const { getShareInfo } = useShare()
	const props = defineProps({
		// 1首页，2店铺详情，3产品详情，4景点详情
		type: { type: [String, Number], default: 1 },
		offsetY: { type: Number, default: 0 },
	})
	const tempFilePath = ref('') // 本地缓存路径
	const getStyle = computed(() => {
		const style = {};
		style.bottom = `${180+props.offsetY}rpx`;
		return style;
	})
	// 分享
	async function handleShare(){
		// #ifdef MP-WEIXIN
		if(unref(tempFilePath)){
			handleShowShareImageMenu()
			return;
		}
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const route = currentPage.route; // 页面路径
		const options = omit(currentPage.options, ['scene']); // 页面参数
		if(getShareInfo(SHARE_ID)) options[SHARE_ID] = getShareInfo(SHARE_ID);
		
		console.log('options', options, objectTOString(options))
		uni.showLoading({ title: '海报生成中···', mask: true });
		try {
			const { data } = await SharePosterGetShareQrcode({
				pathName: route,
				search: objectTOString(options),
				type: props.type
			})
			
			wx.downloadFile({
			  url: data,// getFileUrl(imgUrl),
			  success: (res) => {
				  console.log('SharePosterGetShareQrcode', res)
				if(res.statusCode === 200){
				  tempFilePath.value = res.tempFilePath
				  handleShowShareImageMenu()
				  uni.hideLoading();
				}else{
				  uni.hideLoading();
				  nextTick(() => {
					  uni.showToast({ title: '分享失败', icon: 'none' })
				  })
				}
			  },
			  fail: (res) => {
				  console.log('res', res)
			  }
			})
			
		} catch (error) {
			uni.hideLoading();
			//TODO handle the exception
		}
		// #endif
	}
	
	// 调起wx分享
	function handleShowShareImageMenu(){
		wx.showShareImageMenu({
			path: unref(tempFilePath),
			style: 'v2',
			needShowEntrance: true,
			success: (res1) => {
			  console.log("分享成功", res1);
			},
			fail: (error) => {
			  console.log("分享失败", error);
			}
		})
	}
</script>

<style scoped lang="scss">
	image { height: 100%; width: 100%; }
	.wrap{
		position: fixed;
		right: 32rpx;
		z-index: 9;
		display: flex;
		align-items: flex-end;
		.share-btn{
			width: 80rpx;
			height: 80rpx;
		}
	}
</style>