<script setup lang="ts">
import { orderDateils } from "../orderDetaiols.vue"
import { ref, onMounted } from 'vue';
import { onShow } from "@dcloudio/uni-app";
import { apiImageUrl } from '../../API/api'

// 获取用户信息
const getUserInfo = () => {
    my.getOpenUserInfo({
      fail: (err) => {
        console.error('【授权失败】错误详情:', JSON.stringify(err, null, 2));
      },
      success: (res) => {
        try {
          console.log('【原始响应数据】:', res);

          // 增强解析逻辑
          const response = typeof res.response === 'string'
            ? JSON.parse(res.response)
            : res.response;

          if (response?.response) {
            const userInfo = response.response;
            console.log('【用户信息解析成功】', userInfo);

            // 正确更新用户信息的位置
            user.value.userName = userInfo.nickName || '普通用户';
            user.value.userAvatar = userInfo.avatar || 'https://src.pcsoft.com.cn/d/file/soft/wlgj/wlgx/2017-04-27/20fccb4806f44d7bfafc2360b8934768.jpg';

            // 结构化打印
            console.table({
              nickName: userInfo.nickName,
              avatar: userInfo.avatar,
              gender: userInfo.gender === 'm' ? '男' : '女',
              city: userInfo.city,
              province: userInfo.province
            });

            // 开发环境日志
            if (process.env.NODE_ENV === 'development') {
              console.log('【完整用户信息】:', JSON.stringify(userInfo, null, 2));
            }
          } else {
            console.warn('【响应格式异常】', response);
          }
        } catch (e) {
          console.error('【解析失败】', e);
          console.log('【原始响应内容】:', res.response);
        }
      }
    });
};

// 授权失败处理
const onAuthError = (err) => {
  console.error('【授权流程异常】', JSON.stringify(err, null, 2));
  my.showToast({
    content: `授权失败: ${err.errorMessage || '未知错误'}`,
    duration: 3000
  });
};

// 可以在组件挂载时调用获取用户信息的方法，根据实际情况决定是否保留
onMounted(() => {
  getUserInfo();
});

// 获取用户信息
onShow(() => {
    console.log('=== 我的页面显示，开始检查登录状态 ===');
    
    // 检查本地存储的所有相关数据
    const userInfo = uni.getStorageSync('userInfo');
    const cookie = uni.getStorageSync('cookie');
    const sessionId = uni.getStorageSync('sessionId');
    const isLoggedIn = uni.getStorageSync('isLoggedIn');
    
    console.log('本地存储检查:');
    console.log('userInfo:', userInfo);
    console.log('cookie:', cookie);
    console.log('sessionId:', sessionId);
    console.log('isLoggedIn:', isLoggedIn);
    
    if (!cookie && !sessionId) {
        console.log('缺少认证信息，用户可能未登录');
    }
    
    getLoginUser();
});

const user = ref({
	userAvatar: '',
	userName: '',
	message: ''
})

const loginButtonText = ref<string>(user.value.message === 'ok' ? '退出登录' : '去登录');

const getLoginUser = () => {
    const cookie = uni.getStorageSync("cookie"); // 先获取cookie
    const sessionId = uni.getStorageSync("sessionId"); // 获取sessionId作为备选
    
    console.log('发送请求前检查认证信息:');
    console.log('cookie:', cookie);
    console.log('sessionId:', sessionId);
    
    uni.request({
        url: apiImageUrl + '/api/user/current',
        method: 'GET',
        header: {
            'cookie': cookie || '', // 修正这里
            'sessionId': sessionId || '' // 添加sessionId作为备选
        },
        data: {},
        success: (res) => {
            console.log('获取用户信息响应:', res.data);
            
            user.value.message = res.data.message;
            if (user.value.message === 'ok') {
                // 优先使用详细用户信息接口的数据
                user.value.userName = res.data.data.username || user.value.userName;
                user.value.userAvatar = res.data.data.avatarUrl || user.value.userAvatar;
                loginButtonText.value = '退出登录';
                
                // 如果基础信息接口数据不全，则主动获取详细信息
                if (!user.value.userName || !user.value.userAvatar) {
                    getUserInfo();
                }
            } else {
                console.log('用户未登录，原因:', res.data.message);
                loginButtonText.value = '去登录';
            }
        },
        fail(err) {
            console.log('获取用户信息失败:', err);
        }
    });
};

// 处理登录/退出登录的统一函数
const handleLoginLogout = () => {
	if (user.value.message === 'ok') {
		// 已登录，执行退出操作
		logout();
	} else {
		// 未登录，跳转到登录页
		goToLogin();
	}
}

// 跳转到登录页的函数
const goToLogin = () => {
	uni.navigateTo({
		url: '/pages/login/login'
	});
}

// 退出登录函数
const logout = () => {
    uni.request({
        url: apiImageUrl + '/api/user/logout',
        method: 'POST',
        header: {
            'cookie': uni.getStorageSync("cookie") || ''
        },
        success(res) {
            console.log('退出登录响应:', res);
            // 清理所有本地存储
            uni.removeStorageSync('identify');
            uni.removeStorageSync('cookie');
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('isLoggedIn');
            uni.removeStorageSync('sessionId');
            uni.removeStorageSync('notPay');
            uni.removeStorageSync('cartItems');
            
            // 重置页面状态
            user.value.message = '未登录';
            user.value.userName = '';
            user.value.userAvatar = '';
            loginButtonText.value = '去登录';
            
            uni.reLaunch({
                url: '/pages/login/login'
            });
            uni.showToast({
                title: '退出成功',
                duration: 2000
            });
        },
        fail(err) {
            console.log('退出登录失败:', err);
            // 即使请求失败，也清理本地数据
            uni.removeStorageSync('identify');
            uni.removeStorageSync('cookie');
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('isLoggedIn');
            uni.removeStorageSync('sessionId');
            
            // 重置页面状态
            user.value.message = '未登录';
            loginButtonText.value = '去登录';
        }
    });
};

</script>


<template>
	<scroll-view class="viewport" scroll-y enable-back-to-top>

		<view class="profile">

			 <view class="overview" v-if="user.message === 'ok'" @click="getUserInfo">
			        <navigator hover-class="none">
			          <image 
			            class="avatar" 
			            mode="aspectFill" 
			            :src="user.userAvatar || 'https://默认头像.jpg'"
			          ></image>
			        </navigator>
			        <view class="meta">
			          <view class="nickname">{{ user.userName || '普通用户' }}</view>
			        </view>
			      </view>

			<view class="overview" v-else>
				<navigator hover-class="none">
					<image class="avatar gray" mode="aspectFill"
						src="http://39.101.78.35/images/user_avatar/0/LbLTxpMf-image.png"></image>
				</navigator>
				<view class="meta">
					<navigator hover-class="none" class="nickname">
						未登录
					</navigator>
				</view>
			</view>
		</view>
	</scroll-view>
	<orderDateils></orderDateils>
	<!-- setting -->
	<view class="viewport">
		<view class="list">
			<navigator url="../collect/collect" hover-class="none" class="item arrow">
				收藏店铺列表
			</navigator>
		</view>
		<view class="list">
			<navigator url="../testAI/testAI" hover-class="none" class="item arrow">
				AI
			</navigator>
		</view>
		<!-- 修改这里的点击事件 -->
			<view class="list" @click="handleLoginLogout">
				<view class="item arrow">
					{{ loginButtonText }}
				</view>
			</view>
	</view>
</template>

<style lang="scss">
	page {
		height: 100%;
		overflow: hidden;
		background-color: #4095e5;
	}

	// setting
	.viewport {
		padding: 20rpx;
	}

	.list {
		padding: 0 20rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		border-radius: 10rpx;

		.item {
			line-height: 90rpx;
			padding-left: 10rpx;
			font-size: 30rpx;
			color: #333;
			border-top: 1rpx solid #ddd;
			position: relative;
			text-align: left;
			border-radius: 0;
			background-color: #fff;

			&::after {
				width: auto;
				height: auto;
				left: auto;
				border: none;
			}

			&:first-child {
				border: none;
			}

			&::after {
				right: 5rpx;
			}
		}
	}


	.action {
		text-align: center;
		line-height: 90rpx;
		margin-top: 40rpx;
		font-size: 32rpx;
		color: #333;

		.button {
			background-color: #fff;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
		}
	}

	.logout {
		height: 100rpx;
		line-height: 100rpx;
		font-size: 35rpx;
		text-align: center;
	}

	//setting

	.profile {
		padding-top: 30rpx;
		position: relative;

		.overview {
			display: flex;
			height: 130rpx;
			padding: 0 36rpx;
			color: #fff;
		}

		.avatar {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			background-color: #eee;
		}

		.gray {
			filter: grayscale(100%);
		}

		.meta {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: flex-start;
			line-height: 30rpx;
			padding: 16rpx 0;
			margin-left: 20rpx;
		}

		.nickname {
			max-width: 350rpx;
			margin-bottom: 16rpx;
			font-size: 30rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			color: #000;
		}

		.SchoolCard {
			width: 155px;
			height: 23px;
		}

		.extra {
			display: float;
		}

		.tips {
			float: left;
			padding: 3px 5px 3px 5px;
			font-size: 22rpx;
			color: #000;
			background-color: #fff;
			border: 1px solid #000;
			border-radius: 14px;
		}

		.copy {
			float: right;
			line-height: 23px;
			color: #000;
			font-size: 13px;
			text-decoration: underline;
		}

		.update {
			padding: 3rpx 10rpx 1rpx;
			color: rgba(255, 255, 255, 0.8);
			border: 1rpx solid rgba(255, 255, 255, 0.8);
			margin-right: 10rpx;
			border-radius: 30rpx;
		}
	}
</style>