<template>
    <view class="page-container">
        <!-- 背景图 -->
        <image class="bg-image" src="/static/images/profile/1.png" mode="widthFix"></image>

        <scroll-view class="page-content" style="flex: 1">
            <!-- 用户信息头部 -->
            <view class="header">
                <image class="avatar" src="/static/images/login/2.png" mode="aspectFill"></image>
                <text class="user-name">{{ userName }}</text>
            </view>

            <!-- 信息卡片区域 -->
            <view class="info-cards">
                <!-- 电话卡片 -->
                <view class="info-card">
                    <image class="card-icon" src="/static/images/profile/2.png" mode="aspectFit"></image>
                    <text class="card-label">电话</text>
                    <text class="card-value">{{ userPhone }}</text>
                </view>

                <!-- 部门卡片 -->
                <view class="info-card">
                    <image class="card-icon" src="/static/images/profile/3.png" mode="aspectFit"></image>
                    <text class="card-label">部门</text>
                    <text class="card-value">{{ userDept }}</text>
                </view>
            </view>

            <!-- 通讯录 -->
            <view class="contact-item">
                <text class="contact-text">{{userRole}}</text>
            </view>
			<view class="menu-section">
				<view class="menu-item" @click="handlePassword()">
					<image class="menu-icon" src="/static/images/profile/7.png" mode="aspectFit"></image>
					<text class="menu-title">修改密码</text>
					<text class="menu-arrow">›</text>
				</view>
				
				<view class="menu-item" @longpress="handleVersionClick()">
					<image class="menu-icon" src="/static/images/profile/5.png" mode="aspectFit"></image>
					<text class="menu-title">版本：{{version}}</text>
				</view>
			</view> 
            <!-- 功能菜单 -->
            <!-- <view class="menu-section">
                <view v-for="(item, index) in menuList" :key="index" class="menu-item" @click="handleMenuClick(item)">
                    <image class="menu-icon" src="/static/images/profile/7.png" mode="aspectFit"></image>
                    <text class="menu-title">修改密码</text>
                    <text class="menu-arrow">›</text>
                </view>
            </view> -->

            <!-- 注销账号 -->
            <view class="logout-wrapper">
                <text class="logout-btn" @click="handleLogout">注销账号</text>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="uts">
    import { ref, onMounted } from 'vue'
    import { getUserInfo, getStoreIsKey } from '../../utils/storage'
    import { logout as logoutApi } from '../../api/auth/logout'
    import { useAuth } from '../../composables/useAuth'
	import { encryptAES, decryptAES } from '../../utils/crypto'
	import { getIsKey } from '../../api/auth/login'
	import { getBaseUrl } from '../../utils/request'
	
    // @ts-ignore
    import manifest from '@/manifest.json'

    // 用户信息
    const userName = ref<string>('')
    const userPhone = ref<string>('')
    const userDept = ref<string>('')
	const userRole = ref<string>('')
    
    // 版本信息
    const manifestVersion = manifest.versionName as string | null
    const version = ref<string>(manifestVersion != null ? manifestVersion : '1.0.0')

    // 认证管理
    const auth = useAuth()
    const clearAuth = auth.logout
    const getCurrentAccessToken = auth.getCurrentAccessToken

    // 菜单列表
    type MenuItem = {
        id: number
        title: string
        icon: string
        path?: string
        action?: string
    }

    const menuList = ref<MenuItem[]>([
        {
            id: 1,
            title: '修改密码',
            icon: '/static/images/profile/7.png',
            path: '/pages/profile/password/index'
        },
		{
            id: 2,
            title: '关于版本',
            icon: '/static/images/profile/5.png',
            action: 'version'
        },
        {
            id: 3,
            title: '关于我们',
            icon: '/static/images/profile/6.png',
            path: '/pages/profile/about/index'
        },
        {
            id: 4,
            title: '通用设置',
            icon: '/static/images/profile/8.png',
            path: '/pages/profile/settings/index'
        }
    ])

    // 通讯录点击
    const handleContactClick = (): void => {
        uni.showToast({
            title: '功能开发中',
            icon: 'none'
        })
    }

	const handlePassword = (): void =>{
		uni.navigateTo({
		    url:"/pages/profile/password/index",
		    fail: (err: any) => {
		        uni.showToast({
		            title: '功能开发中',
		            icon: 'none'
		        })
		    }
		})
	}

    // 菜单点击
    const handleMenuClick = (item: MenuItem): void => {
        if (item.action == 'version') {
            uni.showModal({
                title: '版本信息',
                content: `当前版本：v${version.value}`,
                showCancel: false
            })
            return
        }

        if (item.path != null && item.path.length > 0) {
            uni.navigateTo({
                url: item.path,
                fail: (err: any) => {
                    uni.showToast({
                        title: '功能开发中',
                        icon: 'none'
                    })
                }
            })
        }
    }

    // 执行退出登录（必须在 handleLogout 之前定义）
    const doLogout = async (): Promise<void> => {
        try {
            await logoutApi()
        } catch (e: any) {
            console.log('退出登录接口调用失败', e)
        } finally {
			uni.setStorageSync("login_key", "0")
            clearAuth()
        }
    }

    // 退出登录
    const handleLogout = (): void => {
        uni.showModal({
            title: '提示',
            content: '确定要退出登录吗？',
            success: (res) => {
                // 提取属性（any 类型不能直接访问属性）
                const confirm = res.confirm as boolean

                if (confirm) {
                    // 使用异步函数包装
                    doLogout()
                }
            }
        })
    }

	// 安装APK的单独函数
	const installApkFile = (filePath: string): void => {
	  uni.installApk({
		filePath: filePath,
		success: () => {
		  console.log('安装成功');
		  uni.showToast({
			title: '安装成功',
			icon: 'success'
		  });
		},
		fail: (error) => {
		  console.error('安装失败:', error);
		  uni.showToast({
			title: '安装失败',
			icon: 'none'
		  });
		},
		complete: (res) => {
		  console.log('安装完成:', res);
		}
	  });
	}
	
	
	
	const installApkWithProgress = (): void => {		
	    // #ifdef APP-ANDROID
			// 显示下载进度
			uni.showLoading({
				title: '下载中...',
				mask: true
			});
			let donwloadUrl = '';
			donwloadUrl = getBaseUrl() + '/prod-api/profile/app/gxt-release.apk'
		
			// 下载APK
			const downloadTask = uni.downloadFile({
				url: donwloadUrl,
				filePath: `${uni.env.USER_DATA_PATH}/${Date.now()}_test.apk`, // 使用时间戳防止重名
				success: (downloadRes) => {
				uni.hideLoading();
				if (downloadRes.statusCode == 200) {
				// 确认安装
					uni.showModal({
					  title: '安装提示',
					  content: '下载完成，是否立即安装？',
					  success: (modalRes) => {
						if (modalRes.confirm) {
						  installApkFile(downloadRes.tempFilePath);
						}
					  }
					});
				} else {
					uni.showToast({
					  title: '下载失败',
					  icon: 'error'
					});
				  }
				},
				fail: (error) => {
				  uni.hideLoading();
				  uni.showToast({
					title: '下载失败',
					icon: 'none'
				  });
				  console.error('下载失败:', error);
				}
			});
	
			// 监听下载进度
			downloadTask.onProgressUpdate((res) => {
				console.log('下载进度:', res.progress + '%');
				// 如果需要，可以更新UI显示进度
				uni.showLoading({
					title: `下载中 ${res.progress}%`,
					mask: true
				});
			});
		// #endif
		// #ifdef APP-HARMONY
			uni.showToast({
				title: '请登录PC端，扫描二维码下载并安装',
				icon: 'none'
			});
		// #endif
		// #ifdef APP-IOS
			uni.showToast({
				title: '请登录PC端，扫描二维码下载并安装',
				icon: 'none'
			});
		// #endif
	}
	
	// 菜单点击
	const handleVersionClick = (): void => {
	    installApkWithProgress();
	}
	
    // 初始化
    onMounted(() => {
        const userInfo = getUserInfo()
        if (userInfo != null) {
			
            const nickName = userInfo['nickName'] as string | null
			const phone = userInfo['phone'] as string | null
			
			const isKey = getStoreIsKey();
			if(isKey == "1"){
				userName.value = decryptAES(nickName ?? '')
				if (phone != null && phone.length > 0) {
					userPhone.value = decryptAES(phone ?? '')
				}
			}else{
				userName.value = nickName ?? ''
				if (phone != null && phone.length > 0) {
					userPhone.value = phone
				}
			}
            
            const deptName = userInfo['deptName'] as string | null
            if (deptName != null && deptName.length > 0) {
                userDept.value = deptName
            }
			
			const roleNames = userInfo['roleNames'] as string | null
			if (roleNames != null && roleNames.length > 0) {
			    userRole.value = roleNames
			}
        }
    })
</script>

<style lang="scss">
    .page-container {
        position: relative;
        flex: 1;
        background: #f5f8fb;
        padding-top: env(safe-area-inset-top);
    }

    .bg-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 0;
    }

    .page-content {
        position: relative;
        flex: 1;
        padding-bottom: 100rpx;
        z-index: 1;
    }

    .header {
        padding: 80rpx 30rpx 40rpx;
        flex-direction: row;
        align-items: center;

        .avatar {
            width: 120rpx;
            height: 120rpx;
            border: 1rpx solid #ccc;
            border-radius: 60rpx;
            background-color: #fff;
            margin-right: 30rpx;
        }

        .user-name {
            font-size: 40rpx;
            color: #ffffff;
            font-weight: bold;
        }
    }

    .info-cards {
        padding: 0 30rpx;
        flex-direction: row;
        justify-content: space-between;
        margin-bottom: 30rpx;

        .info-card {
            width: 330rpx;
            background-color: #ffffff;
            border-radius: 24rpx;
            padding: 30rpx 24rpx;
            
            /* #ifndef APP-HARMONY */
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
            /* #endif */

            .card-icon {
                width: 48rpx;
                height: 48rpx;
                margin-bottom: 16rpx;
            }

            .card-label {
                font-size: 26rpx;
                color: #666666;
                margin-bottom: 12rpx;
            }

            .card-value {
                font-size: 32rpx;
                color: #333333;
                font-weight: bold;
            }
        }
    }

    .contact-item {
        margin: 0 30rpx 30rpx;
        padding: 30rpx;
        background-color: #ffffff;
        border-radius: 24rpx;
        flex-direction: row;
        align-items: center;
        
        /* #ifndef APP-HARMONY */
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
        /* #endif */

        .contact-icon {
            width: 48rpx;
            height: 48rpx;
            margin-right: 24rpx;
        }

        .contact-text {
            flex: 1;
            font-size: 32rpx;
            color: #333333;
        }

        .contact-arrow {
            font-size: 48rpx;
            color: #cccccc;
            line-height: 48rpx;
        }
    }

    .menu-section {
        margin: 0 30rpx 30rpx;
        background-color: #ffffff;
        border-radius: 24rpx;
        overflow: hidden;
        
        /* #ifndef APP-HARMONY */
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
        /* #endif */

        .menu-item {
            flex-direction: row;
            align-items: center;
            padding: 30rpx;
            border-bottom: 1rpx solid #f0f0f0;

            &:last-child {
                border-bottom: none;
            }

            .menu-icon {
                width: 48rpx;
                height: 48rpx;
                margin-right: 24rpx;
            }

            .menu-title {
                flex: 1;
                font-size: 32rpx;
                color: #333333;
            }

            .menu-arrow {
                font-size: 48rpx;
                color: #cccccc;
                line-height: 48rpx;
            }
        }
    }

    .logout-wrapper {
        margin: 0 30rpx 30rpx;
        background-color: #ffffff;
        border-radius: 24rpx;
        overflow: hidden;
        align-items: center;
        justify-content: center;
        height: 100rpx;
        
        /* #ifndef APP-HARMONY */
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
        /* #endif */

        .logout-btn {
            font-size: 32rpx;
            color: #666666;
            padding: 20rpx 0;
        }
    }
</style>
