<template>
	<view style="padding-bottom: 20px;">
		<view class="top-user-bar">
		  <image class="top-bar-bg" src="@/static/images/mingqi-beij@2x.png" mode="aspectFill"></image>
		  <view class="user-info">
        <image 
          class="avatar" 
          :src="userInfo.avatarUrl || '/static/images/default-avatar.png'" 
          mode="aspectFill"
        ></image>
        <view class="user-info-text">
          <text class="user-name">{{ userInfo.nickName || '未登录' }}</text>
          <text class="user-card">{{ userInfo.cardNo || '' }}</text>
        </view>
      </view>
      <view class="user-menu">
        <view class="menu-item" @click="toCheckLogin('收藏')">
          <image class="menu-icon" src="@/static/images/menu-sc.png" mode="scaleToFill" />
          <text class="menu-txt">收藏</text>
        </view>
        <view class="menu-item" @click="toCheckLogin('借阅')">
          <image class="menu-icon" src="@/static/images/menu-jy.png" mode="scaleToFill" />
          <text class="menu-txt">借阅</text>
        </view>
      </view>
		</view>

    <view class="submenu-box"> 
      <view class="submenu-item" @click="toCheckLogin('我的留言')">
        <uni-icons custom-prefix="iconfont" type="icon-liuyan" size="20"></uni-icons>
        <text class="left-txt">我的留言</text>
      </view>
      <view class="submenu-item" @click="toCheckLogin('个人资料')">
        <uni-icons custom-prefix="iconfont" type="icon-shezhi" size="20"></uni-icons>
        <text class="left-txt">个人资料</text>
      </view>
      <view class="submenu-item" @click="toCheckLogin('修改密码')">
        <uni-icons custom-prefix="iconfont" type="icon-xiugai" size="20"></uni-icons>
        <text class="left-txt">修改密码</text>
      </view>
      <view class="submenu-item" @click="toCheckLogin('挂失读者证')">
        <uni-icons custom-prefix="iconfont" type="icon-UIsheji_menjinxitong-28" size="20"></uni-icons>
        <text class="left-txt">挂失读者证</text>
      </view>
      <view v-if="!!isBindLibraryCard" class="submenu-item" @click="toLogOut()">
        <uni-icons custom-prefix="iconfont" type="icon-tuichu" size="20"></uni-icons>
        <text class="left-txt">退出账号</text>
      </view>
    </view>

    <view>
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog 
					type="info" cancelText="取消" confirmText="确定" 
					title="提示" content="请您绑定读者证!" 
					@confirm="dialogConfirm" @close="dialogClose">
        </uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
      token: "",
      userInfo: {},
      isBindLibraryCard: false 
    };
	},
	onLoad() {
		// this.loadUser()
    this.checkLoginStatus();
	},
	onShow() {
		// this.loadUser()
    this.checkLoginStatus();
	},
	methods: {
    checkLoginStatus() {
      this.loadUser();
      this.isBindLibraryCard = !!this.token;
    },
		// 统一读取用户信息
		loadUser() {
			this.token = uni.getStorageSync("token") || ""
			this.userInfo = uni.getStorageSync("user-info") || {}
		},

		// ✅ 核心：点击任意项都先校验登录
		toCheckLogin(pageName) {
			this.loadUser() // 每次点击都刷新登录状态
			if (!this.token) {
				// 未登录 → 弹窗
				this.dialogToggle()
				return
			}
			// 已登录 → 这里写正常跳转
			// uni.showToast({
			// 	title: `进入【${pageName}】`,
			// 	icon: "none"
			// })
			// 真实跳转示例：
			// uni.navigateTo({
			//   url: `/pages/${pageName}/${pageName}`
			// })
      if(pageName==='借阅'){
        uni.navigateTo({
          url: '/subpkg/pages/myLending/myLending'
        });
      }else if(pageName==='我的留言'){
        uni.navigateTo({
          url: '/subpkg/pages/feedback-list/feedback-list'
        });
      }else if(pageName==='修改密码'){
        uni.navigateTo({
          url: '/subpkg/pages/change-password/change-password'
        });
      }else if(pageName==='收藏'){
        uni.navigateTo({
          url: '/subpkg/pages/collect-list/collect-list'
        });
      }else if(pageName==='个人资料'){
        uni.navigateTo({
          url: '/subpkg/pages/user-info/user-info'
        });
      }
		},

		// 弹出绑定提示
		dialogToggle() {
			this.$refs.alertDialog.open();
		},
    
		// 绑定读者证 → 获取微信信息 → 跳登录页
		dialogConfirm() {
      uni.getUserProfile({
        desc: "绑定读者证",
        success: (res) => {
          const userInfo = JSON.parse(res.rawData);
          uni.setStorageSync("wxUserInfo", userInfo);
          uni.setStorageSync("wxSignature", res.signature);
          
          // 跳转到登录页
          uni.navigateTo({
            url: "/pages/login/login"
          });
        },
        fail: () => {
          uni.showToast({ title: "授权失败", icon: "error" });
        }
      });
		},
    
		dialogClose() {
      console.log('取消')
    },
    toLogOut() {
      // 弹窗确认退出
      uni.showModal({
        title: '确认退出',
        content: '确定要退出当前账号吗？',
        success: (res) => {
          if (res.confirm) {
            // 1. 清空所有登录相关缓存
            uni.removeStorageSync("token");
            uni.removeStorageSync("user-info");
            uni.removeStorageSync("wxUserInfo");
            uni.removeStorageSync("wxSignature");

            // 2. 重置当前页面的登录状态（你的首页变量）
            this.token = "";
            this.userInfo = {};
            this.isBindLibraryCard = false;

            // 3. 提示
            uni.showToast({
              title: '退出成功',
              icon: 'success'
            });

            // 跳回首页
            uni.switchTab({
              url: "/pages/home/home"
            });
            
            // 跳转到登录页
            // uni.navigateTo({
            //   url: "/pages/login/login"
            // });
          }
        }
      });
    },
	}
}
</script>

<style lang="scss" scoped>
.top-user-bar{
  position: relative;
  width: 100%;
  height: 150px;
  display: flex;
  align-items: center;
  color: $uni-white;
  .top-bar-bg{
    position: absolute;
    left: 0;
    top: 0;
    display: block;
    width: 100%;
    height: 100%;
    z-index: 1;
  }
  .user-info{
    position: absolute;
    left: 0;
    top: 0;
    z-index: 99;
    display: flex;
    justify-content: flex-start;
    .avatar{ 
      width: 62px;
      height: 62px;
      border-radius: 31px;
      margin-top: 19px;
      margin-left: 28px;
    }
    .user-info-text{
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: flex-start;
      margin: 26px 16px 0 16px;
      .user-name{
        font-size: 20px;
        font-weight: 500;
        color: #fff;
        line-height: 28px;
      }
      .user-card{
        margin-top: 5px;
        font-size: 12px;
        font-weight: 400;
        color: #fff;
        line-height: 17px;
      }
    }
  }
  .user-menu{
    position: absolute;
    bottom: -60px;
    left: 0;
    background-color: #fff;
    z-index: 99;
    display: flex;
    justify-content: flex-start;
    width: calc(100% - 40px);
    margin: 0 20px;
    border-radius: 6px;
    box-shadow: 0px 2px 15px 0px rgba(0, 0, 0, .1);
    .menu-item{
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 0 30px;
      height: 100px;
      .menu-icon{
        width: 32px;
        height: 32px;
        margin-bottom: 10px;
      }
      .menu-txt{
        color: #636365;
        font-size: 13px;
      }
    }
  }
}


.submenu-box{ 
  margin-top: 80px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .submenu-item{ 
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: calc(100% - 40px);
    background-color: #fff;
    border-bottom: 1px solid #f4f4f4;
    height: 45px;
    padding: 0 20px;
    ::v-deep .uni-icons{
      color: #343434 !important;
    }
    .left-txt{
      color: #343434;
      font-size: 14px;
      width: calc(100% - 50px);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-left: 10px;
    }
  }
}
</style>