<template>
	<view class="i-page">

		<!-- 默认样式 -->
		<view class='i-header'>
			<view class="i-title">
				<text>多典花</text>
			</view>
		</view>

		<!-- 吸顶样式 -->
		<view v-if="isFixed" :class="[isFixed ? 'i-header-fixed' : '', 'i-header']">
			<view class="i-title">
				<text>多典花</text>
			</view>
			<view v-if="hotList && hotList.length" class="hot-tab">
				<view :class="hotIndex == item.id ? 'hot-header-text' : 'hot-show'" v-for="item in hotList"
					:key='item.id'>
					<view class='hot-ative' @click="hotShow(item)">{{ item.title }}</view>
					<view v-show="hotIndex != item.id" class='hot-icon'></view>
					<view v-show='hotIndex == item.id' :class="showUP == false ? 'hot-icon-show-down' : 'hot-icon-show'"
						@click="goUP(item.id)"></view>
				</view>
			</view>
		</view>

		<!-- 用来判断高度的元素 -->
		<view id="box"></view>


		<view v-if='index !== null' class='i-boxs'>
			<!-- Banner 位 -->
			<view v-if="index['bannerList']" class='i-banner'>
				<swiper :autoplay="true" :interval="3000" :duration="1000" style="height: 359rpx;">
					<swiper-item class='swiper-item-i' v-for="(item, index) in JSON.parse(index['bannerList'])"
						:key="item.id" @click='jump(item, index, "banner")'>
						<image :src='item.url' class='banner-item'></image>
					</swiper-item>
				</swiper>
			</view>

			<!-- 金刚位 -->
			<view v-if="index['shortcutList']" class="i-list">

				<template v-for="(item, index) in JSON.parse(index['shortcutList'])">

					<view class='mian-item'
						v-if="item.tager !== 'uni:/subPackage/indexfinance/index,tab'"
						:key="item.id" @click="jump(item, index, 'diamond')">
						<image class='item-img' :src='item.url'></image>
						<view class='item-text'>{{ item.name }}</view>
					</view>

				</template>


			</view>


			<view class="i-malll">

				<!-- 根据滚动条的高度显示隐藏内容 -->
				<view class="hot-tab">
					<view v-for="item in hotList" :class="hotIndex == item.id ? 'hot-header-text' : 'hot-show'"
						:key='item.id'>
						<view class='hot-ative' @click="hotShow(item)">{{ item.title }}</view>
						<view v-show="hotIndex != item.id" class='hot-icon'></view>
						<view v-show='hotIndex == item.id'
							:class="showUP == false ? 'hot-icon-show-down' : 'hot-icon-show'" @click="goUP(item.id)">
						</view>
					</view>
				</view>



				<!-- 商品列表 -->
				<scroll-view class='box-at-home' scroll-y="true" refresher-default-style="none">
					<view class='main-box' v-show="IndexList && IndexList.length > 0">
						<view class='box-item' v-for="(item, index) in IndexList" :key="index" @click="GoDetail(item)">
							<view class='item-top'>
								<image :src="item.goodsImage" class='top-img'></image>
								<i class='top-icon'></i>
							</view>
							<view class='item-footer'>
								<view class='footer-des'>{{ item.goodsName }}</view>
								<view class='footer-box'>
									<view class='box-num'>
										<view class='num-icon'>¥</view>
										{{ item.goodsMoney }}
									</view>
								</view>
								<view class='footer-line'>
									<view class='box-btn'>可置换</view>
									<view class="box-last">{{ item.lookSum }}次浏览</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>


		</view>

		<!-- 更新 -->
		<template v-if="appUpgeadeObj && appUpgeadeObj.downloadUrl">
			<upgrade-Popup :app-upgeade-obj="appUpgeadeObj" @pause='pauseClick'></upgrade-Popup>
		</template>
	</view>
</template>

<script>
import API from '@/server/common'
import { isLogin, switchShowTabbar } from '@/utils/index'
const cacheIndexData = uni.getStorageSync('dataIndex') ? JSON.parse(uni.getStorageSync('dataIndex')) : null;
const indexGoods = uni.getStorageSync('indexGoods') ? JSON.parse(uni.getStorageSync('indexGoods')) : [];


export default {
	data() {
		return {
			IndexList: indexGoods,
			index: cacheIndexData,
			isFixed: false,
			deviceBrand: uni.getSystemInfoSync().deviceBrand,


			// 商品过滤
			hotList: [
				{ title: '浏览量', id: 0 },
				{ title: '价格', id: 1 },
			],
			hotIndex: 0,
			showUP: false,



			params: {
				current: 1,
				size: 50,
				total: 0,
				sort: 'look_sum desc'
			},


			pageNum: 1,
			pageSize: 50,
			total: 0,
			sort: 'look_sum desc',



			hasNextText: '上拉加载更多',
			loadFlag: true,
			hasNextPage: false,


			token: '',

			// 升级对象
			appUpgeadeObj: {}
		}
	},
	// 监听页面滚动
	onPageScroll(e) {
		if (e.scrollTop > this.Topdistance) {
			this.isFixed = true;
		} else {
			this.isFixed = false;
		}
	},
	async onLoad() {
		// 显示隐藏tabBar
		switchShowTabbar()
		// 初始化首页数据
		await this.checkAppVersion()
	},
	async onShow() {

		const that = this;
		// 设置页面滚动条位置
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 0
		})
		setTimeout(() => {
			that.GetTop() // 获取元素距离顶部的距离
		}, 1000)

		// 初始化首页数据
		await this.init()
		await this.initGoods();


		// 首页流量埋点
		this.buryingPoint('app:index_page_view')
	},
	// 页面下拉刷新
	async onPullDownRefresh() {

		await this.init()
		await this.initGoods();

		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	},

	methods: {
		// 初始化首页数据
		async init() {
			try {
				const res = await API.initIndex()
				if (res.success) {
					const data = res.result;
					this.index = data;
					uni.setStorageSync('dataIndex', JSON.stringify(data))
				}
			} catch (err) {
				console.log('初始化首页报错')
			}
		},
		// 获取元素距离顶部的距离
		GetTop() {
			var _this = this
			uni.getSystemInfo({
				success: () => {
					const query = uni.createSelectorQuery().in(this);
					query.select("#box").boundingClientRect((data) => {
						_this.Topdistance = data && data.top
					}).exec();

				}
			})
		},
		// 跳转
		jump(item, index, type) {
			// 埋点开始
			switch (type) {
				case "banner":
					this.buryingPoint('app:index_banner_click')
					break;
				case 'diamond':
					const desc = `app:index_feature${index + 1}_click`
					this.buryingPoint(desc)
					break;
			}
			// 埋点结束

			if (!isLogin()) {
				this.JumpToLogin()
			} else {
				if (item.tager == 'uni:/subPackage/indexfinance/index,tab' || item.tager == 'uni:/pages/indexfinance/index,tab') {
					this.Go('uni:/pages/web/web', 'tab')
				} else {
					let linkUrl = item.tager;
					if (linkUrl.includes('pages/')) {
						linkUrl = linkUrl.replace('pages/', 'subPackage/');
						console.log(linkUrl, '日日')
					}
					this.Go(linkUrl)
				}

			}
		},

		containsWGTExtension(url) {
			return /\.wgt$/i.test(url);
		},
		// 检查版本更新
		checkAppVersion() {
			const self = this
			uni.getSystemInfo({
				success: (res) => {
					const appVersion = uni.getStorageSync('m-header-version')
					let platform = res.platform;
					// 获取本机版本号
					let type;
					platform === "android" ? (type = "ANDROID") : (type = "IOS");
					self.$request(`/pawn/setting/other/appVersion/${type}`, 'GET').then(res => {

						if (res.success == true) {

							const response = res.result.data;
							console.log(appVersion, response.versionName, '版本比较')
							if (appVersion && appVersion < response.versionName) {
								const wgtType = self.containsWGTExtension(response.downloadUrl)
								if (wgtType == true) {
									let checkStatus = uni.getStorageSync('checkVersions')
									console.log(wgtType, '要热更新')
									if (checkStatus == response.versionName) {
										console.log('热更新过了')
										return false
									} else {
										console.log('热更新了')
										self.updateWgt(response.downloadUrl, response.versionName)
									}

								} else {
									console.log('强更了', response)
									self.appUpgeadeObj = response
								}
							}
						}
					})
				}
			})
		},

		// 暂停
		pauseClick(data) {
			this.appUpgeadeObj.downloadUrl = ''
		},

		// 跳转到详情
		GoDetail(item) {
			// 首页流量埋点
			this.buryingPoint('app:index_product_click')
			uni.navigateTo({
				url: '/subPackage/productDetails/productDetails?mydata=' + encodeURIComponent(JSON.stringify({ goodId: item.id }))
			})
		},

		// 切换tab
		hotShow(item) {
			this.hotIndex = item.id
			if (item.id == 0) {
				this.params.sort = 'look_sum desc'
				this.showUP = !this.showUP
			} else {
				this.params.sort = 'goods_money desc'
				this.showUP = !this.showUP
			}
			this.params.current = 1
			this.initGoods()
		},

		goUP(val) {
			// 首页流量埋点
			this.buryingPoint('app:index_price_click')
			this.showUP = !this.showUP
			console.log(this.showUP, '日')
			let sort;
			switch (val) {
				case 0:
					if (!this.showUP) sort = 'look_sum desc'
					else sort = 'look_sum asc'
					break;
				case 1:
					if (!this.showUP) sort = 'goods_money desc'
					else sort = 'goods_money asc'
					break
			}

			this.params.sort = sort;
			this.params.current = 1
			this.initGoods()
		},

		// 查询商品(初始化商品列表)
		initGoods() {
			const params = this.params;
			const { current, size } = this.params
			try {
				this.$request('/pawn/category/getGoodsPage', 'POST', params).then(res => {
					const { total, records } = res.result
					if (current > 1) {
						this.IndexList = this.IndexList.concat(records)
					} else {
						this.IndexList = records
					}

					const hasNextPage = total - size * current > 0 ? true : false //是否有下一页
					this.hasNextPage = hasNextPage
					uni.setStorageSync('indexGoods', JSON.stringify(records))

				}).catch(err => {
					console.log(err, '请求出错')
				})

			} catch {
				console.log(err, '错误信息')
			}

		},

		// 加载更多(该函数去掉了调用,因为不会有第二页的数据)
		lowerMore: function (e) {
			console.log(e, '触底了');
			if (!this.hasNextPage) {
				uni.showToast({
					icon: 'none',
					title: '到底了',
				})
				return false;
			}
			this.params.current = this.params.current + 1
			this.initGoods();
		},

		//wgt更新
		updateWgt(downloadUrl, newVersion) {
			uni.showModal({
				title: '已发现新版本',
				content: '确认更新?',
				showCancel: false,
				success: function (res) {
					uni.setStorageSync('checkVersions', newVersion)
					if (res.confirm) {
						uni.downloadFile({
							url: downloadUrl,
							success: (downloadResult) => {
								plus.runtime.install(downloadResult.tempFilePath, { force: true }, function () {
									//应用热重启,重新启动进入首页
									plus.runtime.restart();
									uni.showModal({
										title: '安装成功!',
										content: '已重新进入应用',
										showCancel: false,
										success: function (res) {
											if (res.confirm) {

												console.log('用户点击确定');
											} else if (res.cancel) {
												console.log('用户点击确定');
											}
										}

									})
								},
									function (e) {
										console.log(e, '安装失败')
										uni.showModal({
											title: '安装失败',
											icon: 'none'
										})
									})
							},
							fail: (err) => {
								uni.showToast({
									title: '下载失败',
									icon: 'none'
								})
							}
						})
					} else if (res.cancel) {
						uni.showToast({
							title: '已取消',
							icon: 'none'
						})
					}
				}
			})
		}
	},

}
</script>

<style src='./index.less' lang="less" scoped></style>