import { useStore } from 'vuex'
import { computed } from 'vue'

export default {
	data() {
		return {
			shareConfig: {
				// 默认分享配置
				title: '',
				desc: '',
				imageUrl: '',
				path: '',
				query: ''
			}
		}
	},

	async onLoad(options) {
		// 构建当前页面路径，包含参数
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		let path = currentPage.route
		
		// 构建查询参数
		if (options && Object.keys(options).length > 0) {
			const queryString = Object.keys(options)
				.map(key => `${key}=${options[key]}`)
				.join('&')
			path = `${path}?${queryString}`
		}
		
		this.shareConfig.path = path
		this.shareConfig.query = options || {}
		
		// 设置默认分享内容
		this.setDefaultShareConfig()
	},

	methods: {
		// 设置默认分享配置
		setDefaultShareConfig() {
			try {
				const store = useStore()
				const configList = computed(() => store.getters.configList)
				
				// 从全局配置中获取默认分享信息
				this.shareConfig.title = configList.value?.applet_info?.paramValueText || '猫妈狗爸伴宠师'
				this.shareConfig.imageUrl = configList.value?.applet_info?.paramValueImage || ''
			} catch (error) {
				console.log('获取分享配置失败:', error)
				// 设置默认值
				this.shareConfig.title = '猫妈狗爸伴宠师'
				this.shareConfig.imageUrl = ''
			}
		},

		// 自定义分享配置
		setShareConfig(config = {}) {
			this.shareConfig = {
				...this.shareConfig,
				...config
			}
		},

		// 获取分享配置
		getShareConfig() {
			return {
				title: this.shareConfig.title,
				desc: this.shareConfig.desc,
				imageUrl: this.shareConfig.imageUrl,
				path: this.shareConfig.path,
				query: this.shareConfig.query
			}
		},

		// 显示分享菜单
		showShareMenu() {
			// #ifdef MP-WEIXIN
			uni.showShareMenu({
				withShareTicket: true,
				success: () => {
					console.log('显示分享菜单成功')
				},
				fail: (error) => {
					console.error('显示分享菜单失败:', error)
				}
			})
			// #endif
		},
	},

	// 微信小程序分享给朋友
	onShareAppMessage(res) {
		return this.getShareConfig()
	},

	// 微信小程序分享到朋友圈
	onShareTimeline(res) {
		return this.getShareConfig()
	},
} 