<template>
	<view class="ezy-yysz-page">
		<view class="icon-title-navBar-box">
			<view @click="handleBack" class="nav-bar-icon"></view>
			<text class="nav-bar-title">应用设置</text>
		</view>
		<view class="yysz-page-box">
			<view class="yysz-row-box">
				<view class="yysz-item img-item" @click="headClick">
					<text>头像</text>
					<icon class="yysz-img-box"
						:style="{backgroundImage: 'url(' + myInfoData.icon + ')'}"></icon>
				</view>
				<view class="yysz-item" @click="nichengClick">
					<text>昵称</text>
					<text class="item-text">{{myInfoData.nickName}}</text>
				</view>
			</view>	
			<view class="yysz-row-box">
				<view class="yysz-item" @click="telClick">
					<text>手机号码</text>
					<text class="item-text">{{myInfoData.userName}}</text>
				</view>
			</view>
			<view class="yysz-row-box">	
				<view class="yysz-item border-item" @click="aboutClick">
					<text>关于我们</text>
				</view>
				<view v-if="loginFlag" class="yysz-item border-item" @click="yinsizhengce">
					<text>隐私政策</text>
				</view>
				<view class="yysz-item border-item" @click="kefudianhua">
					<text>客服与投诉</text>
					<text class="item-text">4001750778</text>
				</view>
				<view v-if="loginFlag" class="yysz-item border-item" @click="yonghuzhuxiao">
					<text>用户注销</text>
				</view>
				 <view class="yysz-item" @click="exitLogin">
					<text>退出登录</text>
				</view>
		</view>
		</view>
		<!-- <CustomTabBar  :currentTabNumber="3"> </CustomTabBar> -->
		<tip-small-dialog ref="exitDialogRef" @confirm-btn="exitBtn" :content="tipContent"></tip-small-dialog>
		<tip-small-dialog ref="zhuxiaoDialogRef" @confirm-btn="zhuxiaoBtn" :content="zhuxiaoContent"></tip-small-dialog>
		<tel-dialog @telClose="telClose" @bindBtn="bindBtn" v-if="telDialogFlag"></tel-dialog>
		<agree-content-dialog ref="agreeContentDialogRef" :agreeType="agreeType"></agree-content-dialog>
		<tip-small-dialog ref="kefuDialogRef" :title="kefuTitle" @confirm-btn="kefuBtn" :content="kefuContent"
			class="kefu-dialog"></tip-small-dialog>
		<nichengDialog ref="nichengDialogRef" @confirm-btn="nichengBtn" title="修改昵称"></nichengDialog>
	</view>
</template>

<script setup>
	import agreeContentDialog from '@/pages/login/agreeContentDialog.vue';
	import {
		toast,
	} from "@/utils/common";
	import cacheManager from '@/utils/cacheManager.js';
	import {
		logout
	} from '@/api/login.js'
	import {
		myInfo,
		zhuxiao,
		duihuanmaCode,
		nichengUpdate,
		myCardList,
		commonCardList,
		getFilePolicy,
		updataHead
	} from '@/api/my.js'
	// import CustomTabBar from '@/components/custom-tabbar/custom-tabbar.vue';
	import {
		onLoad,onShow
	} from '@dcloudio/uni-app';
	import {
		reactive,
		ref
	} from "vue";
	import tipSmallDialog from '@/components/dialog/tipSmallDialog.vue';
	import duihuanmaDialog from '@/components/dialog/duihuanmaDialog.vue';
	import nichengDialog from '@/components/dialog/nichengDialog.vue';
	import tipMiddleDialog from '@/components/dialog/tipMiddleDialog.vue';
	import tipBigDialog from '@/components/dialog/tipBigDialog.vue';
	import telDialog from './components/telDialog.vue'
	
	import { usePermission } from "@/store/permissionStore.js"
	const permissionStore = usePermission()
	
	const agreeType = ref(null);
	const agreeContentDialogRef = ref(null);

	const tipContent = '你确定要执行这个操作吗？';
	const zhuxiaoContent = '你确定要执行这个操作吗？';
	let loginFlag = ref(false);
	let telDialogFlag = ref(false);
	let myInfoData = reactive({
		userImg: '',
		userName: '',
		credit: '',
		vipFlag: '',
		nickName: '',
		icon: '',
	});
	let routerOpt = ref(false);
	let appleCode = ref(null);
	let currentPlatform = ref(null);
	const exitDialogRef = ref(null);
	const zhuxiaoDialogRef = ref(null);
	const nichengDialogRef = ref(null);

	const kefuDialogRef = ref(null);
	const kefuTitle = '提示';
	const kefuContent = '客服电话：4001750778';
	const exitLogin = () => {
		exitDialogRef.value.handleShow();
	}

	function handleBack() {
		uni.switchTab({
			url: '/pages/chanpinMy/my'
		})
	}

	function headClick() {
		chooseImage()
	}

	const checkAlbumPermission = async () => {
		const status = await uni.getSetting()
		if (!status.authSetting['scope.album']) {
			await uni.authorize({
				scope: 'scope.album'
			})
		}
	}
	const chooseImage = async () => {
		try {
		//	await checkAlbumPermission()
			/* #ifdef APP */
			const systemInfo = uni.getSystemInfoSync();
			if (systemInfo.platform != 'ios') {
				if (!await permissionStore.requstPermission('READ_EXTERNAL_STORAGE')) return
			}
			/* #endif */
		
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album'], // 仅限相册选择‌:ml-citation{ref="1" data="citationList"}
				success: (res) => {

					uploadFile(res.tempFilePaths[0])
				},
				fail: (err) => {
					console.error('选择失败:', err)
				}
			})
		} catch (err) {
			uni.showModal({
				title: '权限申请失败',
				content: '请前往设置开启相册权限'
			})
		}
	}

	function updateIcon(data) {
		updataHead({
			icon: data
		}).then(res => {
			if (res.code == 0) {
				uni.showToast({
					title: '上传成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: '上传失败',
				});
			}
		})
	}

	function uploadFile(filePath) {
		const suffix = filePath.split('.').pop();
		let req = {
			prefix: 'resource/',
			suffix: suffix
		}
		getFilePolicy(req).then(res => {
			if (res.code === 0) {
				const policyData = res.data;
				console.log('policyData', policyData);
				uni.uploadFile({
					url: policyData.uploadUrl,
					filePath: filePath,
					name: 'file',
					formData: {
						key: policyData.key,
						policy: policyData.policy,
						OSSAccessKeyId: policyData.accessid,
						signature: policyData.signature,
						success_action_status: '200'
					},
					header: {
						'Content-Type': 'multipart/form-data'
					},
					success(uploadRes) {
						console.log('uploadRes', uploadRes);
						if (uploadRes.statusCode === 200) {
							myInfoData.icon = `${policyData.downloadUrl}/${policyData.key}`;
							updateIcon(myInfoData.icon)
						} else {
							uni.showToast({
								title: '阿里云上传错误，请重试！',
							});
							return false
						}
					},
					fail(err) {
						console.log('err', err);
					}
				});


			}
		})

	}

	function nichengClick() {
		nichengDialogRef.value.handleShow();
	}
	// 退出按钮
	const exitBtn = () => {
		if (loginFlag.value) {
			logout().then(res => {
				toast('退出登录成功')
				cacheManager.clearAll();
				uni.reLaunch({
					url: '/pages/login/index'
				});
			}).catch(err => {
				toast('退出登录失败，请稍后重试')
			})
		} else {
			uni.reLaunch({
				url: '/pages/login/index'
			});
		}

	}
	const zhuxiaoBtn = () => {
		let req = {

		}
		zhuxiao().then(res => {
			cacheManager.clearAll();
			toast('用户注销成功')
			uni.redirectTo({
				url: '/pages/login/index'
			});
		}).catch(err => {
			toast('失败，请稍后重试')
		})
	}

	function yonghuzhuxiao() {
		zhuxiaoDialogRef.value.handleShow();
	}

	function nichengBtn(data) {
		console.log('data', data);
		
		let req = {
			nickName: data
		}
		nichengUpdate(req).then(res => {
			if (res.code == 0) {
				toast('修改成功')
				myInfoData.nickName = data
			} else {
				toast('修改失败请重试或联系管理员')
				return false
			}
		}).catch(err => {

		})
	}

	function yinsizhengce() {
		uni.navigateTo({
			url: '/pages/chanpinMy/yinsizhengce'
		});
		// agreeType.value = 'ystk'
		// agreeContentDialogRef.value.handleShow();
	}

	function kefudianhua() {
		kefuDialogRef.value.handleShow();
	}

	function kefuBtn() {
		kefuDialogRef.value.handleClose();
	}
	// 手机号码
	function telClick() {
		if (loginFlag.value) {
			telDialogFlag.value = true;
		} else {
			youkeDialogRef.value.handleShow();
		}

	}
	// 手机号码绑定
	function bindBtn() {
		telDialogFlag.value = false;
		myGetAuth()
	}
	// 关闭手机号码弹窗
	function telClose() {
		telDialogFlag.value = false;
	}
	// 关于我们
	function aboutClick() {
		uni.navigateTo({
			url: '/pages/chanpinMy/aboutPage'
		});
	}
	// 获取用户数据
	function getMyInfo() {
		myInfo({}).then(res => {
			myInfoData.userName = res.data.userName;
			myInfoData.credit = res.data.credit;
			myInfoData.nickName = res.data.nickName;

			if (res.data.nickName) {
				myInfoData.nickName = res.data.nickName;
			} else {
				myInfoData.nickName = '鹅状元';
			}
			if (res.data.icon) {
				myInfoData.icon = res.data.icon;
			} else {
				getUserImg(res.data.growthType)
			}

		})
	}

	function getUserImg(data) {
		switch (data) {
			case 0:
				myInfoData.icon = 'static/images/my/head-img0.png'
				break;
			case 1:
				myInfoData.icon = 'static/images/my/head-img1.png'
				break;
			case 2:
				myInfoData.icon = 'static/images/my/head-img2.png'
				break;
			case 3:
				myInfoData.icon = 'static/images/my/head-img3.png'
				break;
			default:
				myInfoData.icon = 'static/images/my/head-unlogin-img.png'
				break;

		}
	}

	onLoad((options) => {
		loginFlag.value = true;
		getMyInfo();
	})
</script>