<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">
				<view class="avatar-btn" @click="toUserInfoPage">
					<image v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl" class="avatar-img"></image>
					<image v-else src="@/static/images/avatar.png" class="avatar-img"></image>
				</view>

				<view class="user-info-text">
					<text class="user-name" @click="toUserInfoPage">{{ userInfo.nickName || '未登录' }}</text>
					<text class="user-card" v-if="cardNo">读者证：{{ 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="toUserInfoPage">
				<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>
import config from '@/utils/config'
import { FetchBindRead, FetchFindAllReaderByOpenId } from '@/api/user';

const USER_KEY = 'user-info';       
const READLIST = 'reader-card-list';

export default {
	data() {
		return {
			userInfo: {},
			cardNo: "",
			isBindLibraryCard: false,
		};
	},
	onLoad() {
		this.loadUserInfo();
	},
	onShow() {
		this.loadUserInfo();
	},
	methods:{
    toUserInfoPage() {
      uni.navigateTo({
        url: '/subpkg/pages/user-info/user-info'
      });
    },

		// 调用接口：头像+昵称 → 成功后统一保存缓存
		async bindUserInfo(avatar, nickname) {
			const openId = uni.getStorageSync('wx_login_code') || '';
			const params = {
				avatar,
				libcode: "1201",
				nickname,
				openid: openId
			};
			const res = await FetchBindRead(params);
			const userInfo = {
				nickName: nickname,
				avatarUrl: avatar
			};
			uni.setStorageSync(USER_KEY, userInfo);
			this.userInfo = userInfo;
		},

		// 加载用户信息（从接口获取）
		async loadUserInfo() {
			try {
				const openId = uni.getStorageSync('wx_login_code');
				const readerList = uni.getStorageSync(READLIST) || [];

				// 从接口获取用户信息（昵称、头像）
				if (openId) {
					const res = await FetchFindAllReaderByOpenId({
						libcode: '1201',
						openId: openId
					});

					if (res.code === 200 && res.data) {
						// 只赋值用户信息，不处理读者证
						this.userInfo = {
							nickName: res.data.nickName || res.data.nickname || '',
							avatarUrl: res.data.avatarUrl || res.data.avatar || ''
						};
						uni.setStorageSync(USER_KEY, this.userInfo);
					} else {
						this.userInfo = uni.getStorageSync(USER_KEY) || {};
					}
				} else {
					this.userInfo = uni.getStorageSync(USER_KEY) || {};
				}

				// 找到默认读者证
				const defaultCard = readerList.find(item => item.bindDefault === true);
				this.cardNo = defaultCard ? defaultCard.bindValue : (readerList[0]?.bindValue || '');
				this.isBindLibraryCard = readerList.length > 0;

			} catch (err) {
				// 异常降级：读缓存
				console.error('加载用户信息失败:', err)
				const readerList = uni.getStorageSync(READLIST) || [];
				this.userInfo = uni.getStorageSync(USER_KEY) || {};
				const defaultCard = readerList.find(item => item.bindDefault === true);
				this.cardNo = defaultCard ? defaultCard.bindValue : (readerList[0]?.bindValue || '');
				this.isBindLibraryCard = readerList.length > 0;
			}
		},

		// 校验登录：只根据 有没有读者证 判断
		toCheckLogin(pageName) {
			const readerList = uni.getStorageSync(READLIST) || [];
			
			// 没有绑定读者证 → 弹窗
			if (readerList.length === 0) {
				this.dialogToggle();
				return;
			}

			// 已绑定 → 正常跳转
			const routeMap = {
				'借阅': '/subpkg/pages/myLending/myLending',
				'我的留言': '/subpkg/pages/feedback-list/feedback-list',
				// '修改密码': '/subpkg/pages/change-password/change-password',
				'收藏': '/subpkg/pages/collect-list/collect-list',
				// '个人资料': '/subpkg/pages/user-info/user-info',
				'解绑读者证': '/subpkg/pages/reader-card/reader-card'
			}
			const url = routeMap[pageName]
			if (url) {
				uni.navigateTo({ url })
			}
		},

		dialogToggle() {
			this.$refs.alertDialog.open();
		},
		dialogConfirm() {
			uni.navigateTo({ url: "/pages/login/login" });
		},
		dialogClose() {},

		// 退出登录
		toLogOut() {
			uni.showModal({
				title: '确认退出',
				content: '确定要退出当前账号吗？',
				success: (res) => {
					if (res.confirm) {
						// 清空缓存
						uni.removeStorageSync(USER_KEY);
						uni.removeStorageSync(READLIST);

						// 重置
						this.userInfo = {};
						this.cardNo = "";
						this.isBindLibraryCard = false;

						uni.showToast({ title: '退出成功', icon: 'success' });
						uni.switchTab({ url: "/pages/home/home" });
					}
				}
			});
		},
	}
}
</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-btn {
      background: transparent;
      margin-top: 19px;
      margin-left: 28px;
      &::after{ border: none !important; }
      .avatar-img {
        width: 62px;
        height: 62px;
        border-radius: 50%;
		object-fit: cover;
      }
    }
    .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: 40;
        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>