<template>
  <view class="container">
    <!-- 加载提示 -->
    <view class="loading" v-if="loading">
      <text>加载中...</text>
    </view>
    <!-- web-view组件 -->
    <web-view 
      :src="webviewUrl" 
      @message="handleMessage"
      @load="onLoads"
      @error="onError"
    ></web-view>
  </view>
</template>

<script>
import { H5logoinApp} from '@/api/courseLook.js'
export default {
  data() {
    return {
      loading: true,
	  webviewUrl: uni.getStorageSync('setWebviewUrl'),//动态
      userinfos:{
      	nickname:"",
      	avatar:""
      },
	  usercode:{},
	  
    }
  },
  onLoad(options) {
	  console.log(this.webviewUrl)
	  console.log(options.code)
	  if(options.code){
		  // uni.$emit('us ercode', {  code: options.code });
		  this.loginweixin(options.code)
	  }
    // 生成带参的H5授权页面URL
    // this.webviewUrl = this.generateAuthUrl()
  },
  computed:{
	  appid() {
	  	return this.$store.state.appid
	  },
  },
  methods: {
	  loginweixin(datas){
		 console.log(uni.getStorageSync('H5course'))
		 const h5course=uni.getStorageSync('H5course')
		  var data = {
		  	code: datas,
			appId:this.appid,
			companyId:h5course.companyId,
			companyUserId:h5course.companyUserId,
			projectId:h5course.projectId
		  }
		  H5logoinApp(data).then(res => {
		  		this.res=res
		  		uni.hideLoading();
		  		if (res.code == 200) {
		  			console.log(res)
		  			uni.hideLoading();
		  			uni.showToast({
		  				icon:'none',
		  				title: "成功获取用户信息",
		  			});
					this.userinfos.nickname=res.user.nickname
					this.userinfos.avatar=res.user.avatar
					uni.setStorageSync("userinfos",this.userinfos)
					uni.setStorageSync('userInfo', res.user);
					uni.setStorageSync('TOKEN_WEXIN', res.token);
					this.usercode.code=datas
					this.usercode.userId=res.user.userId
		  			setTimeout(()=>{
						uni.$emit('usercode',this.usercode)
		  				uni.navigateBack({
		  					delta: 1
		  				});
		  			},200)
		  		} else {
					uni.hideLoading();
		  			uni.showToast({
		  			  title: res.msg || '获取用户信息失败',
		  			  icon: 'none'
		  			})
					uni.setStorageSync('vipMsg',res.msg)
					setTimeout(()=>{
						uni.$emit('vipMsg',res.msg)
						uni.navigateBack({
							delta: 1
						});
					},200)
		  		}
		  	},
		  	err => {}
		  ).catch(err=>{
		  	uni.hideLoading();
		  		uni.showToast({
		  			icon:'none',
		  			title: "获取用户信息失败",
		  		});
		  });
	  },
    // 生成授权页面URL，附带小程序传递的参数
    generateAuthUrl() {
      // 获取当前小程序的场景值，用于后续业务处理
      const scene = uni.getLaunchOptionsSync().scene
      
      // 这里替换为你的uniapp H5项目域名
      
      // 拼接参数，可包含小程序特有的信息
      const params = {
        scene,
        appid: 'wx961fadab9bcb792b', // 公众号AppID
        redirect_uri: encodeURIComponent('https://h5.fbylive.com/weixinOauth'),
        scope: 'snsapi_userinfo',
        state: 'wechat_redirect'
      }
      
      // 微信公众号授权URL
      return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${params.appid}&redirect_uri=${params.redirect_uri}&response_type=code&scope=${params.scope}&state=${params.state}#wechat_redirect`
    },
    
    // 处理web-view向小程序发送的消息
    handleMessage(e) {
      console.log('收到web-view消息:', e.detail)
      console.log('收到web-view消息:', e)
      // 获取H5页面传递过来的用户信息
      if (e.detail && e.detail.type === 'user_info') {
        this.userInfo = e.detail.data
         this.token= e.detail.token
        // 存储用户信息到本地
        uni.setStorageSync('userInfo', this.userInfo)
		uni.setStorageSync('TOKEN_WEXIN', this.userInfo)
        
        // 返回上一页或跳转到首页
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },
    
    // web-view加载完成
    onLoads() {
      this.loading = false
      console.log('web-view加载完成')
    },
    
    // web-view加载失败
    onError(e) {
      this.loading = false
      console.error('web-view加载失败:', e)
      uni.showToast({
        title: '页面加载失败',
        icon: 'none'
      })
    }
  }
}
</script>

<style>
.container {
  width: 100%;
  height: 100%;
  position: relative;
}

.loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  z-index: 100;
}

web-view {
  width: 100%;
  height: 100%;
}
</style>    