<script setup>
	// 商品详情
	import {
		ref,
		reactive,
		nextTick,
		getCurrentInstance,
		computed,
	} from 'vue'
	import {
		onLoad,
		onReady,
		onPageScroll,
		onUnload,
	} from '@dcloudio/uni-app'
	import {
		useStore
	} from 'vuex'
	// 接口地址
	import api from '@/api/index.js'
	// 
	import util from '@/common/js/util.js'
	// 头部
	import apex from './components/jy-commodity-head';
	// 商品列表
	import productList from '@/components/shop/productList/productList'
	// 产品详情
	import proDetail from '@/components/shop/detail/detail'
	//底部
	import footerMenu from '@/components/shop/detail/footerMenu';

	const {
		proxy
	} = getCurrentInstance()
	const store = useStore()
	// 产品id
	const id = ref('')
	// 产品详情
	const detail = reactive({})
	// 当前登录的用户信息
	const userinfo = computed(() => {
		return store.state.userinfo
	})

	onLoad(option => {
		if (option.productId) id.value = option.productId
		// 获取产品详情
		getDetail()
		// 添加商品浏览记录
		addBrowsing()
		// 开启监听
		addListener()
	})

	onReady(() => {
		// 
	})

	// 销毁监听
	onUnload(() => {
		removeListener()
	})

	onPageScroll((ev) => {
		if (ev.scrollTop > 44) proxy.$refs.apexRef.headerActive = true
		else proxy.$refs.apexRef.headerActive = false
	})

	// 开启监听
	function addListener() {
		// 监听商品详情
		uni.$on('commodityDetail', (data) => {
			// 
			if (detail.id == data.id) getDetail()
		})
	}

	// 移除监听
	function removeListener() {
		uni.$off('commodityDetail')
	}

	// 获取详情
	function getDetail() {
		api.shop.productDetail({
			query: {
				userId: userinfo.value.id,
				// 产品id
				productionId: id.value
			}
		}).then(rs => {
			if (rs.code == 200) {
				Object.assign(detail, {}, rs.data)
				return
			}
			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}

	// 添加商品浏览记录
	function addBrowsing() {
		// 验证登录
		util.isLogin(() => {
			// 添加浏览记录
			api.shop.addBrowsing({
				data: {
					userId: userinfo.value.id,
					goodsId: id.value
				},
			}).then(rs => {
				if (rs.code != 200) console.log('addbrows err', rs.msg)
			})
		})
	}

	/**
	 * 详情
	 * @param {Object} ev 修改的详情
	 */
	function handleDetail(ev) {
		Object.assign(detail, {}, ev)
	}
</script>

<template>
	<view class="app pr">
		<!-- 头部 -->
		<apex ref="apexRef" :detail="detail" />

		<!-- 获取详情 -->
		<proDetail :id="id" :detail="detail" />

		<!-- 精选 -->
		<view class="recommend mlr20">
			<productList :choicenessTitle="true" />
		</view>

		<!-- 底部 -->
		<footerMenu :detail="detail" @update="handleDetail" />
	</view>
</template>

<style lang="scss" scoped>
	// 
</style>