<route lang="jsonc" type="page">
{
	"needLogin": true,
	"layout": "default",
	"style": {
		"navigationStyle": "custom"
	}
}
</route>

<template>
	<view class="">
		<!-- 修改昵称 -->
		<wd-popup v-model="showEditNicknamePopup" lock-scroll custom-style="border-radius: 32rpx 32rpx 0rpx 0rpx;" position="bottom">
            <view class="relative pb-56rpx">
                <view class="absolute top-18rpx right-30rpx" @click="showEditNicknamePopup = false">
                    <wd-img width="60rpx" height='60rpx' :src="`${OSS}icon/icon_close.png`"></wd-img>
                </view>

                <view class="text-36rpx text-[#121212] leading-50rpx text-center pt-50rpx pb-40rpx">修改昵称</view>

                <view class="mt-70rpx mx-48rpx">
					<wd-input
						clearable
						type="text" 
						placeholder="请输入昵称" 
						v-model="nickname" 
						no-border
						custom-class="!bg-[#F6F7F8] !rounded-16rpx !text-30rpx !leading-48rpx" 
						custom-input-class="!h-104rpx !pl-60rpx">
							<template #prefix>
								<view class="ml-30rpx font-bold text-30rpx leading-48rpx text-[#303133]">
									昵称
								</view>
							</template>
					</wd-input>
				</view>

				<view class="mt-22rpx text-26rpx leading-36rpx text-[#909399] mx-48rpx">昵称限制1-10字符，一个汉字为一个字符</view>

				<view class="mx-48rpx h-90rpx leading-90rpx rounded-8rpx text-center mt-112rpx text-[#fff]" :class="nickname ? 'bg-[#4C9F44]' : 'bg-[#A5CFA1]'" @click="Profile.handleSaveNickname">保存</view>
            </view>
        </wd-popup>

		<!-- 退出登录 -->
        <wd-popup v-model="showLogoutPopup" lock-scroll custom-style="border-radius: 32rpx 32rpx 0rpx 0rpx;" position="bottom">
            <view class="relative pt-54rpx pb-74rpx">
                <view class="text-[#303133] text-36rpx leading-46rpx text-center">您确定要退出该账号吗？</view>
				<view class="mt-76rpx">
					<view class="bg-[#4C9F44] h-90rpx leading-90rpx mx-60rpx rounded-8rpx text-center text-[#fff]" @click="Profile.handleLogout">
						退出登录
					</view>

					<view class="bg-[#fff] border-2rpx border-solid border-[#9CA3AF] h-90rpx leading-90rpx mx-60rpx rounded-8rpx text-center text-[#303133] mt-40rpx" 
						@click="showLogoutPopup = false">
							取消
					</view>
				</view>
            </view>
        </wd-popup>

		<view>
			<navbar title="个人信息" custom-class='!bg-[#F6F7F8]'></navbar>
		</view>

		<view class="bg-white rounded-16rpx mt-20rpx mx-30rpx px-30rpx py-32rpx">
			<!-- 头像 -->
			<view class="flex justify-between items-center mb-54rpx">
				<view class="font-400 text-[#303133] text-30rpx leading-42rpx">头像</view>
				<view class="flex justify-end">
					<view class="flex items-center">
						<view class="mr-10rpx">
							<wd-upload
								:header="{'token': token}"
								:file-list="fileList" 
								:limit="1"
								image-mode="scaleToFill"
								:action="action"
								@success="Profile.handleUploadSuccess">
								<wd-img width="64rpx" height="64rpx" :src="user.avatar" mode="aspectFill" round />
							</wd-upload>
						</view>
						<wd-icon name="arrow-right" size="32rpx" color="#C0C4CC" />
					</view>
				</view>
			</view>

			<!-- 昵称 -->
			<view class="flex justify-between items-center mb-54rpx" @click="showEditNicknamePopup = true">
				<view class="font-400 text-[#303133] text-30rpx leading-42rpx">昵称</view>
				<view class="flex justify-end">
					<view class="flex items-center">
						<view class="font-400 text-[#303133] text-30rpx leading-42rpx">
							{{ user.nickname }}
						</view>
						<view>
							<wd-icon name="arrow-right" size="32rpx" color="#C0C4CC" />
						</view>
					</view>
				</view>
			</view>

			<view class="flex justify-between items-center mb-54rpx">
				<view class="font-400 text-[#303133] text-30rpx leading-42rpx">修改手机号</view>
				<view class="flex justify-end">
					<view class="flex items-center">
						<wd-button type="text" open-type="getPhoneNumber" @getphonenumber="Profile.handleToEditMobile" custom-class="!p-0 !m-0 !bg-transparent !h-auto !leading-normal !w-300rpx !text-right">
							<view class="font-400 text-[#303133] text-30rpx leading-42rpx" v-if="maskedMobile">
								+86  {{ maskedMobile }}
							</view>
							<view class="font-400 text-[#303133] text-30rpx leading-42rpx" v-else>点击绑定</view>
						</wd-button>
					</view>
				</view>
			</view>
			
			<view class="flex justify-between items-center">
				<view class="font-400 text-[#303133] text-30rpx leading-42rpx">版本号</view>
				<view class="flex justify-end">
					<view class="flex items-center">
						<view class="font-400 text-[#303133] text-30rpx leading-42rpx">
							2.14.17
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bg-white rounded-16rpx mt-144rpx mx-30rpx px-30rpx py-32rpx text-center font-400 text-[#303133] text-30rpx leading-42rpx" @click="showLogoutPopup = true">
			退出登录
		</view>
	</view>
</template>


<script lang="ts" setup>
    import {toast} from '@/utils/toast'
	import { getUserInfo, updateUserInfo } from '@/api/user'
	import type { IUserResult } from '@/api/types/user'
	import { router } from '@/utils/tools'
	import { useUserStore } from '@/store'
	import { getMobileByMnp } from '@/api/user'

	const OSS = inject('OSS')
	const showLogoutPopup = ref<boolean>(false) // 是否显示退出登录弹出框

	// 上传文件
	const fileList = ref<any[]>([])
	const action = 'https://76458.com/api/upload/image' // 仅做测试使用，实际请换成真实上传接口

	// 修改昵称
    const showEditNicknamePopup = ref<boolean>(false) // 是否显示退款详情弹出框
	const nickname = ref<string>('') // 昵称

	// 用户信息相关
	const user = ref<IUserResult>({
		id: 0,
		sn: 0,
		sex: "未知",
		account: "",
		nickname: "",
		real_name: "",
		avatar: "",
		collect_count: 0,
		coupon_count: 0,
		create_time: "",
		has_auth: false,
		has_password: false,
		member: 0,
		mobile: "",
		user_money: "0.00",
		version: ""
	})

	const token = ref<string>('') // 用户token

	onLoad(() => {
		token.value = uni.getStorageSync('token')

		Profile.handleInit()
	}) 
	
	const Profile = {
		/**
		 * 初始化用户信息
		 */
		handleInit: () => {
			getUserInfo().then(res => {
				user.value = res
			})
		},

		/**
		 * 图片选择/删除
		 * @param e 
		 */
		handleChange: (e: any) => {
			console.log("🚀 ~ e:", e)
		},

		handleUploadSuccess: async (e: any) => {
			try {
				const response = JSON.parse(e.file.response)
				if (response.code) {
					const avatarUrl = response.data.url
					const url = avatarUrl.replace(import.meta.env.VITE_UPLOAD_IMAGE_URL, '')
					await updateUserInfo({ field: 'avatar', value: url })
					user.value.avatar = avatarUrl
					toast.info('头像上传成功')
				} else {
					throw new Error('上传失败')
				}
			} catch (error) {
				toast.info('上传失败')
			}
		},

		/**
		 * 保存昵称
		 */
		handleSaveNickname: async () => {
			if (!nickname.value) {
            	toast.info('请输入昵称')
				return
			}

			await updateUserInfo({ field: 'nickname', value: nickname.value })
			showEditNicknamePopup.value = false
			user.value.nickname = nickname.value
			toast.info('昵称修改成功')
		},

		/**
		 * 修改手机号
		 */
		handleToEditMobile: async (e: any) => {
			const res = await getMobileByMnp(e.code)
			Profile.handleInit()
		},

		/**
		 * 退出
		 */
		handleLogout: async () => {
			const userStore = useUserStore()
			await userStore.logout()
			if (!userStore.isLoggedIn) {
				toast.info('退出成功')
				setTimeout(() => {
					router.reLaunch('/pages/my/my')
                }, 1000)
			}
		}
	}

	/**
	 * 掩码处理手机号
	 */
	const maskedMobile = computed(() => {
		if (!user.value.mobile) return ''
		// 只处理11位手机号
		return user.value.mobile.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
	})
</script>

<style lang="scss">
	page {
		background: $cz-page-background;
	}
</style>
