<template>
	<view class="main">
		<!-- nav -->
		<!-- #ifdef APP-PLUS -->
		<view class="nav-head">
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view class="nav-head-H5">
				<!-- #endif -->
				<u-button class="serviceButton" color="#323045" @click="getContact">{{ i18n.customerService }}
				</u-button>
				<view class="languageBtn" @click.stop="languageShow = true">
					{{ langTrue }}
				</view>
				<!-- popups弹窗 -->
				<u-overlay :show="languageShow" @click="languageShow = false" :opacity="0">
					<language-popups v-model="languageShow" :popData="languageData" @tapPopup="tapPopup">
					</language-popups>
				</u-overlay>
			</view>
			<!-- 轮播图 -->
			<!-- #ifdef APP-PLUS -->
			<u-swiper class="swiper" :list="swiperList" @click="bannerClick" previousMargin="48rpx" nextMargin="80rpx"
				circular :autoplay="true" radius="32rpx" bgColor="rgba(0,0,0,0)" height="360rpx">
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<u-swiper class="swiper" :list="swiperList" @click="bannerClick" previousMargin="48rpx"
					nextMargin="80rpx" circular :autoplay="true" radius="32rpx" bgColor="rgba(0,0,0,0)" height="360rpx"
					style="margin-top: 145rpx;">
					<!-- #endif -->
				</u-swiper>
				<!-- 消息 -->
				<view class="message" @click="go('/pages/me/notification')">
					<u-icon class="icon" name="../../static/home/ic_proclamation.png" size="60rpx" width="60rpx">
					</u-icon>
					<!-- <view class="text">{{ i18n.homeMessage }}</view> -->
					<u-notice-bar class="notice" :text="messageList" icon="" fontSize="24rpx" bgColor="#211F32"
						color="#fff" direction="column">
					</u-notice-bar>
				</view>
				<!-- 三个按钮 -->
				<view class="btnDiv">
					<view class="item" @click="goto('recharge')">
						<u--image class="img" :showLoading="true" src="../../static/home/img_recharge.png"
							width="123rpx" height="123rpx"></u--image>
						<view class="text">{{ i18n.Recharge }}</view>
					</view>
					<view class="item" @click="goto('mine')">
						<u--image class="img" :showLoading="true" src="../../static/home/img_Mine.png" 
						width="123rpx" height="123rpx"></u--image>
						<view class="text">{{ i18n.Mine }}</view>
					</view>
					<view class="item" @click="goto('subcription')">
						<u--image class="img" :showLoading="true" src="../../static/home/img_Subcription.png"
							width="123rpx" height="123rpx"></u--image>
						<view class="text">{{ i18n.Subcription }}</view>
					</view>
					<view class="item" @click="goto('contractOrder')">
						<u--image class="img" :showLoading="true" src="../../static/home/img_Order.png"
							width="123rpx" height="123rpx"></u--image>
						<view class="text">{{ i18n.Order }}</view>
					</view>
				</view>
				<!-- 步数 -->
				<view class="steps">
					<view class="content">
						<view class="title">{{ i18n.TodaySteps }}</view>



						<view id="chart" :stepsNum="stepsNum" :stepTarget="stepTarget"
							:change:stepTarget="echarts.stepTargetReceive" :change:stepsNum="echarts.receive"
							style="width: 280rpx;height:280rpx; font-size: 40rpx;">
						</view>


						<!-- <canvas id="chart" ref="chart" style="width: 280rpx;height:280rpx; font-size: 40rpx;"></canvas> -->
						<u-button class="button" color="#00E8A2" @click="closeModalShow=true">{{ i18n.ReceiveEarnings }}
						</u-button>
					</view>
				</view>

				<!-- close确认框 -->
				<u-modal :show="closeModalShow" :confirmText="i18n.Confirm" :cancelText="i18n.Cancel"
					:showCancelButton="true" :title="i18n.WarmTips" :content='i18n.WarmTipsText' @confirm="closeConfirm"
					@cancel="closeModalShow = false" confirmColor="#00E8A2" cancelColor="#96959E">
				</u-modal>

				<!-- 播放器 -->
				<view class="videoList" v-for="(item, index) in videoList" :key="index" @click="playVideo(item.adText)">
					<view class="videoImage" :style="`background-image: url(${baseURL+item.adImgPath});background-repeat: no-repeat;
			background-size: cover;`">
						<view class="VideoBg">
							<view class="VideoLogo"></view>
							<view class="VideoTitle">{{ item.adTitle }}</view>
						</view>
					</view>
				</view>
				<video class="video" v-show="videoShow" id="video" :enable-progress-gesture="false" autoplay="true"
					:src="videoUrl" controls x5-video-player-type="h5-page" @fullscreenchange="ifStopVideo"></video>
				<!-- 通知弹出层 -->
				<view class="">
					<u-popup class="popup" :show="popupShow" round="32rpx" mode="center" @close="popupShow = false"
						@open="popupShow = true" bgColor="#211F32" :customStyle="{
					margin: 'auto 102rpx auto 118rpx',
				}">
						<view class="content">
							<scroll-view scroll-y="true" style="max-height: 388rpx;" scroll-with-animation="true"
								@touchmove.stop.prevent="">
								<view class="" v-html="contentFirst"></view>
							</scroll-view>
							<u-button class="button" color="#00E8A2" @click="toRead" :throttleTime="500">{{i18n.OK}}</u-button>
						</view>
					</u-popup>
				</view>


				<!-- 		<view class="" @click="startStep">
			开始记步
		</view>
		<view class="" @click="startStep">
			步数：{{stepCount}}
		</view> -->
				<!-- tabBar -->
				<tab-bar :selectActive="1"></tab-bar>
		</view>
</template>

<script>
	import languagePopups from '@/components/language-popups/language-popups.vue'
	import languageData from '@/utils/language/config'
	import api from '@/utils/api'
	import constant from '@/utils/constant.js';
	// 引入echarts
	// import * as echarts from 'echarts';
	// let videoPlayerObj = {};
	let videoPlayer;
	let myChart;
	let StepCounter = uni.requireNativePlugin('HF-Step-module');
	export default {
		name: 'home',
		components: {
			languagePopups
		},
		data() {
			return {
				closeModalShow: false,
				stepCount: '',
				stepResult: '',
				// 展示的公告数据未读的
				contentFirst: '',
				// 记录还剩多少未读的 是否显示弹框
				noticeId: null,
				// 公告
				notice: [],
				// 公告详情
				noticeDetail: {},
				baseURL: '',
				languageShow: false,
				langTrue: languageData[0].title || 'English',
				languageData,
				popupShow: false,
				messageList: [],
				swiperList: [

				],
				bannerList: [],
				videoShow: false,
				videoUrl: '',
				videoList: [],
				option: null,
				stepsNum: 0, // 当前步数
				stepTarget: 5000, // 目标步数
				myChart: null,
			}
		},
		onLoad() {
			this.baseURL =  constant.BASE_URL
			this.getbanner();
			this.noticeList();
			this.getUserInfoBalance();
		},
		onShow() {

			// 生成播放器队列对象
			// this.videoList.forEach((item, index) => {
			// 	const VideoPlayer = uni.createVideoContext(`video-${index}`, this)
			// 	videoPlayerObj[`video-${index}`] = VideoPlayer
			// });
			videoPlayer = uni.createVideoContext(`video`, this);

			// this.$nextTick(() => {
			// 	this.initChart()
			// })
			if (uni.getStorageSync('langTrue')) {
				this.langTrue = uni.getStorageSync('langTrue')
			}
			// #ifdef APP-PLUS
			this.getSept()
			// this.startStep() 
			// this.resStartStep()
			this.updateSteps('show');
			this.stepsNum = 5000;
			// #endif
			// #ifdef H5
			this.stepsNum = 5000;
			this.updateSteps();
			// #endif
		},

		onHide() {
			this.stopAllVideoPlay()
		},
		computed: {
			i18n() {
				return this.$t('home')
			}
		},
		methods: {
			// 更新步数逻辑
			updateSteps(soucre) {
				var today = this.$index.formatyymmdd(new Date().getTime());
				var stepsNum_date = uni.getStorageSync("stepsNumDate");

				var isUpdate = false;
				// console.log(today)
				// console.log(uni.getStorageSync("stepsNumDate"))
				// console.log(stepsNum_date)

				if (stepsNum_date) {
					if (today != stepsNum_date.date) {
						uni.setStorageSync("stepsNumDate", null);

					} else {
						if (this.stepsNum == 0) {
							this.stepsNum = stepsNum_date.newStepsNum;
						}
						if (parseInt(this.stepsNum) > parseInt(stepsNum_date.stepsNum)) {

							uni.setStorageSync("stepsNumDate", {
								stepsNum: stepsNum_date.stepsNum,
								date: today,
								newStepsNum: this.stepsNum
							});
							if (soucre) {
								isUpdate = true;
							}
						}
					}


				} else {
					isUpdate = true;
				}
                
				if (isUpdate&&this.stepsNum>0) {
					this.$api.updateSteps({
						steps: this.stepsNum
					}).then(res => {
						// console.log(res, 'res更新')
						uni.setStorageSync("stepsNumDate", {
							stepsNum: this.stepsNum,
							date: today,
							newStepsNum: this.stepsNum
						});
					})
				}
				// console.log(this.stepsNum)
			},

			bannerClick(i) {
				// #ifdef APP-PLUS
				plus.runtime.openURL(this.bannerList[i])
				// #endif
				// #ifdef H5
				var href = this.bannerList[i]
				window.open(href, '_blank');
				// #endif

			},
			// 获取用户余额信息
			getUserInfoBalance() {
				api.userAccount().then(res => {

				})
			},
			// 捐步
			closeConfirm() {
				this.$api.receivStepsAward().then(res => {
					uni.$u.toast(this.$t("markets").Succeeded)
				})
				this.closeModalShow = false
			},
			//  开启计步服务
			getSept() {
				try {
					//整个应用设置一次即可，停止计步后需重新调用，所有接口调用必须先开启计步服务
					StepCounter.startStep((res) => {
						console.log(res, '步数res');
						this.stepCount = res.stepCount
						this.stepsNum = res.stepCount;
						// 暂时写死5000
						this.stepsNum = 5000;
						this.updateSteps();
						//res.stepCount 当天累计步数
					}, (res) => {
						// console.log(res)
						let callback = res.callback
						if (callback == "stepStatus") {
							let status = res.status;
							if (1 == status) {
								//安卓gps定位服务未开
								// console.log('安卓gps定位服务未开')
							} else if (2 == status || 5 == status) {
								//权限被禁止
								//this.gotoSettings()
								// console.log('权限被禁止')
							} else if (3 == status) {
								//允许运动权限（处理安卓权限问题）
								//this.startStep()
								// console.log('允许运动权限（处理安卓权限问题）')
							}
						}

					});
				} catch (e) {
					// console.error("获取步数出错", e)
				}
			},
			startStep() {
				//获取本次记录的步数，重启应用后需要重新开始记录
				StepCounter.getRecordStep((res) => {
					//res.result == true 获取记录成功，否则错误
					//res.stepCount 记录的步数
					// console.log(res.result)
					// console.log(res.stepCount)
				});
			},
			resStartStep() {
				//如需重新记录，再次调用此接口即可
				StepCounter.startRecordStep((res) => {
					//res.result == true 开始记录成功，否则错误
					// console.log(res.result)
				});
			},


			// 获取客服联系方式
			getContact() {
				api.customerService({}).then(res => {
					if (res.errCode == 'SYS.0012') {
						uni.$u.toast(res.errMsg);
					} else {
						// #ifdef APP-PLUS
						// console.log(res.url)
						plus.runtime.openURL(res.url)
						// #endif
						// #ifdef H5
						var href = res.url
						window.open(href, '_blank');
						// #endif

					}
				})
			},

			// 获取未读的公告
			getNoReadNotice() {
				for (var i = 0; i < this.notice.length; i++) {
					if (this.notice[0].isRead == 'no') {
						this.contentFirst = this.notice[i].content
						this.noticeId = this.notice[i].id
						this.popupShow = true
					}
				}
				// 如果循环都是已读的就关闭弹框
				// if (!this.noticeId) {
				// 	this.popupShow = false
				// }
			},
			// 读公告
			toRead() {
				this.popupShow = false
				api.noticeRead({
					noticeId: this.noticeId
				}).then(res => {
					// this.noticeId = null;
					// this.messageList=[];
					// this.noticeList();
				})
			

			},
			go(url) {
				uni.navigateTo({
					url: url
				})
			},


			// 公告
			noticeList() {
				api.noticeList({}).then(res => {
					this.notice = res;
					for (var i = 0; i < res.length; i++) {
						this.messageList.push(res[i].title)
					}
					if (this.notice[0].isRead == 'no') {
						this.contentFirst = this.notice[0].content
						this.noticeId = this.notice[0].id
						this.popupShow = true
					}
				
				})
			},
			// 轮播
			getbanner() {
				api.indexBanner({
					'mark': 'APP_INDEX'
				}).then(res => {
					// this.bannerList = res
					for (var i = 0; i < res.length; i++) {
						this.swiperList.push(this.baseURL + res[i].adImgPath)
						this.bannerList.push(res[i].adUrl)
					}
					this.videoList = res
					// banner图按照接口返回的顺序 但是底部视频倒序放 
					this.videoList = this.videoList.reverse();
				})
			},
			// 弹出语言选择框
			laug() {
				this.laugValue = true;
			},
			// 切换语言
			tapPopup(e) {
				this._i18n.locale = e.language
				this.$store.commit('setLanguage', e.language)
				this.langTrue = e.title
				uni.setStorageSync('langTrue', e.title)
				// uni.redirectTo({
				// 	url: '/pages/home/index'
				// })
				uni.reLaunch({
					url: '/pages/home/index'
				})
			},
			/**
			 *  在跳转其他页面时是暂停全部视频
			 * @param {*} e 
			 */
			stopAllVideoPlay() {
				videoPlayer.pause()
			},
			/**
			 * 根据全屏状态与暂停视频
			 * @param {*} e 
			 */
			ifStopVideo(e) {
				if (e.detail.fullScreen) {
					videoPlayer.play()
				} else {
					this.videoShow = false
					videoPlayer.pause()
				}
			},
			/**
			 * 播放视频
			 * @param {*} data 
			 */
			playVideo(data) {
				this.videoUrl = data;
				this.videoShow = true;
				videoPlayer.requestFullScreen({
					direction: 0
				})
			},
			/**
			 * 跳转
			 */
			goto(page) {
				// console.log(page);
				let url = '';
				switch (page) {
					case 'recharge':
						url = '/pages/recharge/recharge'
						break;
					case 'mine':
						url = '/pages/mine/mine'
						break;
					case 'subcription':
						url = '/pages/subscription/index';
						break;
					case 'contractOrder':
						url = '/pages/markets/contractOrder';
						break;
					default:
						break;
				}
				if (url) {
					this.stopAllVideoPlay()
					// console.log(url);
					if (page === 'subcription') {
						uni.reLaunch({
							url,
						})
						return;
					}
					uni.navigateTo({
						url,
					});
				}

			},


		}
	}
</script>

<script module="echarts" lang="renderjs">
	let myChart
	export default {
		mounted() {
			// this.initEcharts();
			if (typeof window.echarts === 'object') {
				this.initEcharts()
			} else if (typeof window.echarts === 'function') {
				this.initEcharts()
			} else {
				// 动态引入较大类库避免影响页面展示
				const script = document.createElement('script');
				// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
				script.src = './static/echarts.min.js';
				script.onload = this.initEcharts.bind(this);
				document.head.appendChild(script);
			}
		},

		methods: {
			receive(newValue, oldValue, ownerVm, vm) {
				// console.log(newValue, '变化')
				this.initEcharts()
				// if(!this.myChart){
				// 	this.initEcharts()
				// }else{
				// 	this.myChart.setOption(this.option)
				// }

			},
			stepTargetReceive(newValue, oldValue, ownerVm, vm) {

			},
			initEcharts() {
				this.initChart()
				this.myChart = echarts.init(document.getElementById('chart'))
				// 观测更新的数据在 view 层可以直接访问到
				this.myChart.setOption(this.option)
				// console.log('变化initEcharts')
			},
			onClick(event, ownerInstance) {
				// 调用 service 层的方法
				ownerInstance.callMethod('onViewClick', {
					test: 'test'
				})
			},
			initChart() {
				this.option = {
					title: {
						text: this.stepsNum,
						// 副标题
						subtext: "",
						// 主副标题间距
						itemGap: 0,
						left: 'center',
						top: 'center',
						// 主标题样式
						textStyle: {
							fontSize: '20',
							color: '#fff'
						},
					},
					series: [{
						name: '环形饼图',
						type: 'pie',
						roundCap: true,
						radius: ['48%', '70%'],
						avoidLabelOverlap: false,
						label: {
							show: false,
							position: 'center'
						},
						itemStyle: {
							// 设置扇形的阴影
							shadowBlur: 0,
							shadowColor: '#00E8A2',
							shadowOffsetX: 'center',
							shadowOffsetY: 'center',

						},
						data: [{
								value: +this.stepsNum / this.stepTarget,
								name: '步数',
								itemStyle: {
									color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
										offset: 1,
										color: '#00E8A2'
									}, ]),
									borderRadius: 0,
								}
							},
							{
								value: (this.stepTarget - this.stepsNum) / this.stepTarget,
								name: '剩余步数',
								itemStyle: {
									color: '#A1A0A8',

								}
							}
						]
					}]
				}

				// myChart.setOption(this.option, true);
				window.addEventListener('resize', () => {
					myChart.resize();
				});
			}
		},
		watch: {
			// 如果 `question` 发生改变，这个函数就会运行
			columData: function(newQuestion, oldQuestion) {

				// this.updateEcharts(this.option)
			}
		},
	}
</script>

<style lang="scss" scoped>
	/deep/.u-popup__content {
		background: #323045;

		.u-modal__title {
			color: #fff;
		}

		.u-modal__content__text {
			text-align: center;
		}
	}

	/deep/ .u-modal__content__text {
		color: #96959E !important;
	}

	.main {
		padding-bottom: 198rpx; // 避免底部TabBar盖住内容


		.nav-head-H5 {
			position: fixed;
			top: 0rpx;
			height: 112rpx;
			font-size: 36rpx;
			color: #fff;
			width: 100%;
			background-color: #15141F;
			z-index: 8;
			border-bottom: 4rpx solid #323045;

			.serviceButton {
				display: inline-block;
				width: 286rpx;
				height: 70rpx;
				line-height: 70rpx;
				border-radius: 90rpx;
				font-size: 28rpx;
				color: #F2FE8D !important;
				padding: 0;
				margin: 20rpx 180rpx 0 48rpx;
				vertical-align: top;
			}

			.languageBtn {
				display: inline-block;
				box-sizing: border-box;
				width: 180rpx;
				position: relative;
				margin: 38rpx 48rpx 0 0;
				font-size: 24rpx;
				height: 36rpx;
				line-height: 36rpx;
				text-align: center;
				padding-left: 12rpx;

				&::before {
					display: block;
					position: absolute;
					content: '';
					background-image: url(../../static/home/map.png);
					background-repeat: no-repeat;
					background-size: 36rpx;
					width: 36rpx;
					height: 36rpx;
					top: 0rpx;
					left: 0rpx;
				}

				&::after {
					display: block;
					position: absolute;
					content: '';
					background-image: url(../../static/home/pull-down.png);
					background-repeat: no-repeat;
					background-size: 24rpx;
					width: 24rpx;
					height: 24rpx;
					top: 12rpx;
					right: 0rpx;
				}

			}

		}

		.nav-head {
			position: fixed;
			top: 0rpx;
			height: 112rpx;
			font-size: 36rpx;
			color: #fff;
			padding-top: 88rpx;
			width: 100%;
			background-color: #15141F;
			z-index: 8;
			border-bottom: 4rpx solid #323045;


			.serviceButton {
				display: inline-block;
				width: 286rpx;
				height: 70rpx;
				line-height: 70rpx;
				border-radius: 90rpx;
				font-size: 28rpx;
				color: #F2FE8D !important;
				padding: 0;
				margin: 20rpx 180rpx 0 48rpx;
				vertical-align: top;
			}

			.languageBtn {
				display: inline-block;
				box-sizing: border-box;
				width: 180rpx;
				position: relative;
				margin: 38rpx 48rpx 0 0;
				font-size: 24rpx;
				height: 36rpx;
				line-height: 36rpx;
				text-align: center;
				padding-left: 12rpx;

				&::before {
					display: block;
					position: absolute;
					content: '';
					background-image: url(../../static/home/map.png);
					background-repeat: no-repeat;
					background-size: 36rpx;
					width: 36rpx;
					height: 36rpx;
					top: 0rpx;
					left: 0rpx;
				}

				&::after {
					display: block;
					position: absolute;
					content: '';
					background-image: url(../../static/home/pull-down.png);
					background-repeat: no-repeat;
					background-size: 24rpx;
					width: 24rpx;
					height: 24rpx;
					top: 12rpx;
					right: 0rpx;
				}

			}
		}



		.swiper {
			margin-top: 236rpx;
		}

		.message {
			position: relative;
			margin: 24rpx 24rpx 32rpx;
			height: 96rpx;
			background: #211F32;
			border-radius: 16rpx;
			overflow: hidden;

			.icon {
				position: absolute;
				top: 18rpx;
				left: 20rpx;
			}

			.notice {
				width: 574rpx;
				margin-left: 80rpx;
				margin-top: 10rpx;
			}

			.text {
				position: absolute;
				top: 18rpx;
				left: 92rpx;
				height: 68rpx;
				line-height: 32rpx;
				width: 574rpx;
				font-size: 24rpx;
				// 超出字符省略成...
				overflow: hidden;
				text-overflow: ellipsis;
				word-wrap: break-word;
				display: -webkit-box; //兼容
				white-space: normal !important;
				-webkit-line-clamp: 2; //显示行数
				-webkit-box-orient: vertical;
			}
		}

		.btnDiv {
			margin: 32rpx 34rpx;

			.item {
				display: inline-block;
				width: 172rpx;
				text-align: center;

				.img {
					margin: 0 26rpx 16rpx;
				}
			}
		}

		.steps {
			margin: 0 32rpx;
			width: 686rpx;
			height: 472rpx;
			background-color: #211F32;
			background-image: url(../../static/home/img_People.png);
			background-repeat: no-repeat;
			background-size: contain;
			border-radius: 16px;

			.content {
				margin-left: 246rpx;
				height: 100%;
				display: flex;
				justify-content: space-evenly;
				align-items: center;

				flex-direction: column;

				.title {
					font-size: 48rpx;
					height: 64rpx;
					line-height: 64rpx;
				}

				.chart {
					width: 180rpx;
					height: 180rpx;
				}

				.button {
					width: 386rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 40rpx;
					font-size: 24rpx;
					color: #15141F !important;
					padding: 0;
					margin-right: 24rpx;
				}
			}
		}

		.videoList {

			.videoImage {
				margin: 32rpx 32rpx 0;
				width: 686rpx;
				height: 360rpx;
				border-radius: 32rpx;

				.VideoBg {
					box-sizing: border-box;
					padding-top: 96rpx;
					width: 100%;
					height: 100%;
					background-color: rgba(0, 0, 0, 0.6) !important;

					.VideoLogo {
						width: 96rpx;
						height: 96rpx;
						margin: 0 auto;
						background-image: url(../../static/home/ic_play.png);
						background-repeat: no-repeat;
						background-size: 96rpx;
					}

					.VideoTitle {
						font-size: 48rpx;
						text-align: center;
					}
				}
			}
		}

		.video {
			// position: fixed;
			top: 0;
			z-index: 9;
		}


		.popup {

			.content {
				padding: 60rpx 48rpx;

				&::before {
					display: block;
					position: absolute;
					content: '';
					background-image: url(../../static/home/img_Speaker.png);
					background-repeat: no-repeat;
					background-size: contain;
					width: 112rpx;
					height: 112rpx;
					top: -32rpx;
					left: -16rpx;
				}

				.button {
					width: 386rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 40rpx;
					font-size: 24rpx;
					color: #15141F !important;
					padding: 0;
					margin: 20rpx auto 0;
				}
			}



		}

	}
</style>
