<template>
	<view class="start-index">
		<view v-if="tabberPageLoadFlag[0]" :style="{display: currentIndex === 0 ? '' : 'none'}">
			<tn-nav-bar customBack>
				<view slot="back" class='tn-custom-nav-bar__back' @click="reFetchData()">
					<text v-if="!loading" class="tn-icon-circle-arrow" style="font-size: 30px;"></text>
					<view style="margin-top:6px" v-if="loading"><tn-loading :size="46"></tn-loading></view>
				</view>
			
				<view slot="default" style="display: flex;">
					<view style="flex:1;margin-left:25px;">
						<text>我要什么</text>
					</view>
					<view>
						<text class="tn-icon-add-fill" style="font-size: 30px;margin-right: 4px;"
							@click="addButton()"></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[1]" :style="{display: currentIndex === 1 ? '' : 'none'}">
			<tn-nav-bar customBack>
				<view slot="back" class='tn-custom-nav-bar__back' @click="reFetchData()">
					<text v-if="!loading" class="tn-icon-circle-arrow" style="font-size: 30px;"></text>
					<view style="margin-top:6px" v-if="loading" ><tn-loading :size="46"></tn-loading></view>
				</view>
			
				<view slot="default" style="display: flex;">
					<view style="flex:1;margin-left:25px">
						<text>我有什么</text>
					</view>
					<view>
						<text class="tn-icon-add-fill" style="font-size: 30px;margin-right: 4px;"
							@click="addButton()"></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[2]" :style="{display: currentIndex === 2 ? '' : '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">
        <Message ref="message"></Message>
      </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></Auth>
		<tn-tabbar v-model="currentIndex" :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: 'trust-fill',
						inactiveIcon: 'trust'
					},
					{
						title: '我有什么',
						activeIcon: 'team-fill',
						inactiveIcon: 'team'
					},
					// {
					//   title: '发现',
					//   activeIcon: 'rocket',
					//   inactiveIcon: 'cube',
					//   activeIconColor: '#FFFFFF',
					//   inactiveIconColor: '#FFFFFF',
					//   iconSize: 50,
					//   out: true
					// },
					{
						title: '供需发布平台',
						activeIcon: 'add-fill',
						inactiveIcon: 'add-circle',
						// count: 12
					},
					{
						title: '我的',
						activeIcon: 'my-fill',
						inactiveIcon: 'my'
					}
				],
				// tabbar当前被选中的序号
				currentIndex: 0,
				// 自定义底栏对应页面的加载情况
				tabberPageLoadFlag: [],
				shareData:{}
			}
		},
		onLoad(options) {
			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();
			// uni.login({
			// 	success(res) {
			// 		 console.error(res);
			// 		 that.loginByCode(res.code);
			// 	},
			// 	fail(res) {
			// 		 console.error(res);
			// 		uni.hideLoading();
			// 	}
			// });

		},
		onShow(){
			if (this.currentIndex === 3&&this.$refs.mine) {
				this.$refs.mine.getContentRectInfo();
			}
			if (this.currentIndex === 1&&this.$refs.comm) {
				this.$refs.comm.fetchData();
			}
			if (this.currentIndex === 2&&this.$refs.discovery) {
				this.$refs.discovery.fetchData();
			}
		},
		methods: {
			// 切换导航
			switchTabbar(index) {
				this._switchTabbarPage(index)
				if (index !== 1) {
					this.$refs?.commRef?.stopAllVideo()
				}
			},
			//获取openId,unionid
			getOpenId(code) {
				const that = this;
				request.post('/wxma/code2Session',{
						code: code,
						platType: "slb",
						mpType: "engineer",
					}).then(res=>{
						console.error(res);
						if(res.success){
							//登录成功
							uni.setStorageSync('userMap', JSON.stringify(res.resultMap));
						}
					
					})
				// wx.request({
				// 	method: 'post',
				// 	url: 'http://slb-m.dev.ml1993.com/lx-api/wxma/code2Session', //仅为示例，并非真实的接口地址
				// 	data: {
				// 		code: code,
				// 		platType: "slb",
				// 		mpType: "engineer",
				// 	},
				// 	header: {
				// 		'content-type': 'application/json' ,// 默认值
				// 		platType: "slb",
				// 		mpType: "engineer",
				// 	},
				// 	success(res) {
				// 		console.warn(res);
				// 		//unionid存到本地
				// 		wx.setStorage({
				// 			key: "frontlixiangsid",
				// 			data: res.data.resultMap.frontlixiangsid
				// 		}, {
				// 			key: "userId",
				// 			data: res.data.resultMap.unionid
				// 		})

						
				// 	}
				// })
			},

			loginByCode(frontId) {
				const that = this;
				uni.setStorageSync('loginStatus', 'false');
				wx.getUserInfo({
				  success: function(res) {
					console.error(res);
					request.post("/slbMpAutoLogin", {
					 		code:frontId, 
					 	    appType:'ma',
							encryptedData:res.encryptedData,
							iv: res.iv
					 	}, {
						login: false,
						warn:false,
						loading:false
					}).then(res2=>{
						console.error(res2);
						if(res2.success){
							//登录成功
							uni.setStorageSync('loginStatus', 'true');
							uni.setStorageSync('userMap', JSON.stringify(res2.resultMap));
							uni.setStorageSync('userNo', res2.resultMap.accountName);
						}else{
							console.error(12345);
							uni.setStorageSync('loginStatus', 'false');
							
							//登录失败,
							uni.login({
								success(res) {
									 console.error(res);
									 that.getOpenId(res.code);
								},
								fail(res) {
									 console.error(res);
									uni.hideLoading();
								}
							});
							 
						}
						console.error(res2);
					});
					 // uni.request({
					 // 	method: 'post',
					 // 	url: 'http://slb-m.dev.ml1993.com/lx-api/slbMpAutoLogin', //仅为示例，并非真实的接口地址
					 // 	data: {
					 // 		code:frontId, 
					 // 	    appType:'ma',
						// 	encryptedData:res.encryptedData,
						// 	iv: res.iv
					 // 	},
					 // 	header: {
					 // 		'content-type': 'application/json', // 默认值
					 		 
					 // 		platType: "slb",
					 // 		mpType: "engineer",
					 // 	},
					 // 	success(res2) {
					 // 		console.error(res2);
					 // 		//unionid存到本地
					 		 
					 // 	}
					 // })
					 
				  }
				})
				 
				
			},

			// 瀑布流导航页面滚动到底部
			tabbarPageScrollLower(e) {
				if (this.currentIndex === 0) {
					this.$refs.home.loadMore();
				}
				if (this.currentIndex === 1) {
					this.$refs.comm.loadMore();
				}
				if (this.currentIndex === 2) {
					
				}
			},
			 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 === 0) {
					console.error('this');
					this.$refs.home.reFetchData();
				}
				if (this.currentIndex === 1) {
					console.error('this');
					this.$refs.comm.reFetchData();
				}
				setTimeout(() => {
					this.triggered = false;
					this._freshing = false;
				}, 2000)
			},
			onRestore() {
				this.triggered = false; // 需要重置
				console.error("onRestore");
			},
			
			addButton() {
				
				if (!uni.getStorageSync('userNo')) {
					uni.showToast({
						title: '请登录',
						icon:'none'
					})
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return false;
				} else {
					uni.navigateTo({
						url: this.currentIndex === 0?'/circlePages/circle':'/circlePages/addShare'
					})
				}
				//未登录，去登录
				//已登录，去新增第一步
			},
			reFetchData() {
				 
					if (this.currentIndex === 0) {
						console.error('this');
						this.$refs.home.reFetchData();
					}
					if (this.currentIndex === 1) {
						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
			},
			// 获取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 === 0?'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 === 0) {
						this.$refs.home.hideSheet();
					}
					if (this.currentIndex === 1) {
						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',
						// imageUrl: 'https://test-oss.lx-device.com/userFeedback/1733213748200dRV.png'
					};
				}
				
				
			},
			
			onShareAppMessage0: function(option) {
				if(option.from=="button"){
					if (this.currentIndex === 0) {
						this.$refs.home.hideSheet();
					}
					if (this.currentIndex === 1) {
						this.$refs.comm.hideSheet();
					}
				}
				
				return {
					title: '速立保',
					path: '/pages/index/index',
				};
			},
		}
	}
</script>

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