<template>
	<view class="start-index">
		<view v-if="tabberPageLoadFlag[1]" :style="{display: currentIndex === 1 ? '' : 'none'}">
			<tn-nav-bar customBack>
				<view slot="back" class='tn-custom-nav-bar__back' >
					 
					<image style="width: 28px;height: 28px;margin-left:4px"  @click="reFetchData()" src="../../static/tu/reload.png"></image>
					<image style="width: 28px;height: 28px;margin-left:12px"  @click="addButton()" src="../../static/tu/add.png"></image>
					 
				</view>
			
				<view slot="default" style="display: flex;">
					<view style="flex:1;">
						<text :style="{fontSize:(wxFontSize)+'px'}">我要什么</text>
					</view>
					 
				</view>
			</tn-nav-bar>
			<scroll-view class="custom-tabbar-page"  :style="{marginTop: vuex_custom_bar_height + 'px'}" lower-threshold="60"  scroll-y :refresher-enabled="true" :refresher-triggered="triggered" @refresherpulling="onPulling" @refresherrestore="onRestore" @refresherrefresh="onRefresh" enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Home ref="home"></Home>
				
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlag[2]" :style="{display: currentIndex === 2 ? '' : 'none'}">
			<tn-nav-bar customBack>
				<view slot="back" class='tn-custom-nav-bar__back'>
					<image style="width: 28px;height: 28px;margin-left:4px"  @click="reFetchData()" src="../../static/tu/reload.png"></image>
					<image style="width: 28px;height: 28px;margin-left:12px"  @click="addButton()" src="../../static/tu/add.png"></image>		 
				</view>
			
				<view slot="default" style="display: flex;">
					<view style="flex:1;">
						<text :style="{fontSize:(wxFontSize)+'px'}">我有什么</text>
					</view>
				</view>
			</tn-nav-bar>
			<scroll-view class="custom-tabbar-page" :style="{marginTop: vuex_custom_bar_height + 'px'}" scroll-y :refresher-enabled="true" :refresher-triggered="triggered" lower-threshold="60" @refresherrestore="onRestore" @refresherrefresh="onRefresh"  @refresherpulling="onPulling" enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Comm ref="comm"></Comm>
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlag[0]" :style="{display: currentIndex === 0 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Discovery ref="discovery"></Discovery>
			</scroll-view>
		</view>
		<view v-if="tabberPageLoadFlag[3]" :style="{display: currentIndex === 3 ? '' : 'none'}">
			<scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
				<Mine ref="mine"></Mine>
			</scroll-view>
		</view>
		<Auth ref="authRef"></Auth>
		<tn-tabbar v-model="currentIndex" :iconSize="wxFontSize+23" :fontSize="wxFontSize+6" :list="tabbarList" activeColor="#1d60b1" inactiveColor="#AAAAAA"
			activeIconColor="#1d60b1" :animation="true" :safeAreaInsetBottom="true" @change="switchTabbar"></tn-tabbar>
			<canvas type="2d" id="myCanvas" style="width: 450px; height: 450px;left:9000px;position:fixed;"></canvas>
		
	</view>
</template>

<script>
	import Auth from '../index/autoLogin.vue'
	import Home from '../home/home.vue'
	import Comm from '../comm/comm.vue'
	import Discovery from '../discovery/discovery.vue'
	import Mine from '../mine/mine.vue'
    import request from '../../utils/request'
	export default {
		components: {
			Auth,
			Home,
			Comm,
			Discovery,
			Mine
		},
		data() {
			return {
				triggered: false,
				_freshing: false,
				// 底部tabbar菜单数据
				tabbarList: [
					{
						title: '供需发布平台',
						activeIcon: 'add-fill',
						inactiveIcon: 'add-circle',
						// count: 12
					},
					{
						title: '我要什么',
						activeIcon: 'trust-fill',
						inactiveIcon: 'trust'
					},
					{
						title: '我有什么',
						activeIcon: 'team-fill',
						inactiveIcon: 'team'
					},
					{
						title: '我的',
						activeIcon: 'my-fill',
						inactiveIcon: 'my'
					}
				],
				// tabbar当前被选中的序号
				currentIndex: 0,
				// 自定义底栏对应页面的加载情况
				tabberPageLoadFlag: [],
				shareData:{},
				wxFontSize:17
			}
		},
		onLoad(options) {
			const appBaseInfo = wx.getAppBaseInfo();
			this.wxFontSize = uni.getStorageSync('fontSize')||appBaseInfo.fontSizeSetting||17;
			
			const index = Number(options.index || 0)
			// 根据底部tabbar菜单列表设置对应页面的加载情况
			this.tabberPageLoadFlag = this.tabbarList.map((item, tabbar_index) => {
				return index === tabbar_index
			})
			this._freshing = false;
			this.switchTabbar(index);
			let that = this;
			uni.hideShareMenu();	
			
		},
		onShow(options){
			if (this.currentIndex === 3&&this.$refs.mine) {
				this.$refs.mine.fetchData();
			}
			if (this.currentIndex === 2&&this.$refs.comm) {
				this.$refs.comm.fetchData();
			}
			if (this.currentIndex === 0&&this.$refs.discovery) {
				this.$refs.discovery.fetchData();
			}
			if(uni.getStorageSync('lastTime')){	
				//5*60s过期
				if(new Date().getTime()-uni.getStorageSync('lastTime')>5*60*1000||!uni.getStorageSync('userNo')){
					uni.setStorageSync('lastTime',new Date().getTime());
					if(this.$refs.authRef&&!uni.getStorageSync('loginOut')){
						// this.$refs.authRef.reLogin();
					}
				}
			}else{
				uni.setStorageSync('lastTime',new Date().getTime())
			}
			if(uni.getStorageSync('nextPage')&&uni.getStorageSync('userNo')){
				let nextPage = uni.getStorageSync('nextPage')
				uni.removeStorageSync('nextPage');
				uni.navigateTo({
					url: nextPage
				}) 
			}else{
				uni.removeStorageSync('nextPage')
			}
			if (wx.canIUse('getUpdateManager')) {
			  const updateManager = wx.getUpdateManager();
			  updateManager && updateManager.onCheckForUpdate((res) => {
				if (res.hasUpdate) {
				  updateManager.onUpdateReady(() => {
					uni.showModal({
					  title: '更新提示',
					  content: '新版本已经准备好，是否重启应用？',
					  success: (res) => {
						if (res.confirm) {
						  uni.clearStorageSync() // 更新完成后刷新storage的数据
						  updateManager.applyUpdate()
						}
					  }
					})
				  })
			
				  updateManager.onUpdateFailed(() => {
				//     uni.showModal({
				//       title: '已有新版本上线',
				//       content: '小程序自动更新失败，请删除该小程序后重新搜索打开哟~~~',
				// showCancel: false
				//     })
					uni.reLaunch({
						url:'/pages/index/index'
					})
				  })
				} else {
				  //没有更新
				}
			  })
			}
			uni.redirectTo({
				url:'/pages/home/home'
			})
		},
		methods: {
			// 切换导航
			switchTabbar(index) {
				this._switchTabbarPage(index)
			},
			// 瀑布流导航页面滚动到底部
			tabbarPageScrollLower(e) {
				if (this.currentIndex === 1) {
					this.$refs.home.loadMore();
				}
				if (this.currentIndex === 2) {
					this.$refs.comm.loadMore();
				}
			},
			onPulling(e) {
				console.log("onpulling", e);
				if(e.detail.deltaY<0){
					return
				}
				this.triggered = true
			}, 
			onRefresh(){
				if (this._freshing) return;
				this._freshing = true;
				if (this.currentIndex === 1) {
					this.$refs.home.reFetchData();
				}
				if (this.currentIndex === 2) {
					this.$refs.comm.reFetchData();
				}
				setTimeout(() => {
					this.triggered = false;
					this._freshing = false;
				}, 2000)
			},
			onRestore() {
				this.triggered = false; // 需要重置
			},
			
			addButton() {
				
				if (!uni.getStorageSync('userNo')) {
					uni.showToast({
						title: '请登录',
						icon:'none'
					})
					uni.setStorageSync('nextPage',this.currentIndex === 1?'/circlePages/circle':'/circlePages/addShare');
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return false;
				} else {
					uni.navigateTo({
						url: this.currentIndex === 1?'/circlePages/circle':'/circlePages/addShare'
					})
				}
				//未登录，去登录
				//已登录，去新增第一步
			},
			reFetchData() {
				if (this.currentIndex === 1) {
					console.error('this');
					this.$refs.home.reFetchData();
				}
				if (this.currentIndex === 2) {
					console.error('this');
					this.$refs.comm.reFetchData();
				}
			},

			// 切换导航页面
			_switchTabbarPage(index) {
				const selectPageFlag = this.tabberPageLoadFlag[index]
				if (selectPageFlag === undefined) {
					return
				}
				if (selectPageFlag === false) {
					this.tabberPageLoadFlag[index] = true
				}
				this.currentIndex = index
				if (this.currentIndex === 0&&this.$refs.discovery) {
					this.$refs.discovery.fetchData();
				}
				if (this.currentIndex === 3&&this.$refs.mine) {
					this.$refs.mine.fetchData();
				}
			},
			// 获取canvas实例和ctx画笔
			  getMyCanvasAndCtx(id) {
			    //id  canvas 2d的id
			    return new Promise((resolve) => {
			
			      const query = wx.createSelectorQuery();
			
			      query
			
			        .select(`#${id}`)
			
			        .fields({
			
			          node: true,
			
			          size: true,
			
			        })
			
			        .exec((res) => {
			
			          const canvas = res[0].node;
			
			          const ctx = canvas.getContext("2d");
			
			          const dpr = wx.getSystemInfoSync().pixelRatio;
			
			          canvas.width = res[0].width * dpr;
			
			          canvas.height = res[0].height * dpr;
			
			          ctx.scale(dpr, dpr);
			
			          const data = {
			
			            canvas,
			
			            ctx,
			
			          };
			
			          resolve(data);
			
			        });
			
			    });
			
			  },
			
			 sleep(time) {
			     return new Promise((resolve) => setTimeout(resolve, time));
			 },
			async initCanvas(){
				 // 保存画布
				   const { ctx, canvas } = await this.getMyCanvasAndCtx("myCanvas");
				    ctx.save();
				  
				    ctx.font = "24px";
				    // ctx.textAlign = "center";
				    ctx.fillText(this.shareData.company||this.shareData.contactPerson, 0, 32);

					// ctx.textAlign = "center";
					ctx.fillText(this.shareData.content, 0, 72);
					
				    // sleep 500毫秒，等待图片加载完成 不然有可能圆形头像没有加载出来
				
				    await this.sleep(500);
				
				    let url = null;
				    
				    // 需要自行封装 canvasToTempFilePath
				
				    const res = await wx.canvasToTempFilePath({ canvas });
				
				    url = res.tempFilePath;
				
				    return url;
				 
			},
			addLog(shareData){
				const that = this;
				let params= {
					bisNo:shareData.bisNo,
					bisType:this.currentIndex === 1?'1':'2',
					userNo:uni.getStorageSync('userNo')
				};
				
				request.post('/slbForward/add',{slbForward:JSON.stringify(params)},{
							  headers: {
							  	'Content-Type': 'application/json', // 默认值
							  },
				}).then(res=>{
							 
				})
			},
			onShareAppMessage: function(option) {
				if(option.from=="button"){
					if (this.currentIndex === 1) {
						this.$refs.home.hideSheet();
					}
					if (this.currentIndex === 2) {
						this.$refs.comm.hideSheet();
					}
					
					
					
					this.shareData=option.target.dataset.coupon;
					this.addLog(this.shareData);
					 const promise = new Promise(async (resolve) => {
					
					      const url = await this.initCanvas();
					
					      resolve({
					
					        // title: `速立保`,
					
					        path: `/pages/index/detail/detail?id=`+this.shareData.bisNo+'&isNeed='+(this.shareData.isNeed?1:0),
					
					        // imageUrl: url,
					
					      });
					
					    });
					    
					    // 默认参数
					    return {
					      // title: `速立保`,
					      path: `/pages/index/detail/detail?id=`+this.shareData.bisNo+'&isNeed='+(this.shareData.isNeed?1:0),
					      promise,
					    };
					 
				}else{
					return {
						// title: '速立保',
						path: '/pages/index/index',
					};
				}
				
				
			}
		}
	}
</script>

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