<!-- 用户设置 -->
<template>
	<s-layout :title="$t('setting.set')" class="set-userinfo-wrap">
		<uni-forms
			:model="state.model"
			:rules="state.rules"
			labelPosition="left"
			border
			class="form-box"
		>
			<view class="bg-white">
				<uni-list :border="false" class="">
					<uni-list-chat
						clickable
						:avatar-circle="true"
						:title="state.model?.nickname"
						:avatar="state.model?.avatar"
						:note="$t('setting.signature')"
						@tap="sheep.$router.go('/pages/user/info')"
					>
						<view class="chat-custom-right">
							<text
								class="_icon-forward"
								style="color: #bbbbbb; font-size: 32rpx"
							></text>
						</view>
					</uni-list-chat>
					<uni-list-item
						clickable
						@tap="sheep.$router.go('/pages/user/address/list')"
						:title="$t('setting.physical_address_management')"
						showArrow
						:border="false"
					/>
					<uni-list-item
						clickable
						@tap="sheep.$router.go('/pages/user/dummyAddress/list')"
						:title="$t('setting.virtual_address_management')"
						showArrow
						:border="false"
					/>
					
					<uni-list-item
					title="支付宝账号"
					showArrow
					clickable
					:border="false"
					 @tap="onChangeAlipayAccount">
						<template v-slot:body>
							<p style="width: 100%"
								>{{$t('setting.alipay_account')}}&nbsp;&nbsp;{{alipayAccount?alipayAccount:'未绑定'}}
							</p>
						</template>
						
					</uni-list-item>
					<uni-list-item 
					title="银行卡" 
					showArrow
					clickable
					:border="false"
					@tap="onChangeBankAccount">
						<template v-slot:body>
							<p style="width: 100%"
								>{{$t('setting.bank_card')}}&nbsp;&nbsp;{{bankAccount?bankAccount:'未绑定'}}
							</p>
						</template>
					</uni-list-item>
					<!-- <uni-list-item
						clickable
						@tap="sheep.$router.go('/pages/user/invoice/list')"
						title="发票抬头管理"
						showArrow
						:border="false"
					/> -->
					<!-- <uni-list-item
						:clickable="!userInfo.mobile"
						@tap="sheep.$router.go('/pages/user/address/list')"
						title="实名认证"
						showArrow
						:border="false"
					>
						<template v-slot:body>
							<p style="width: 100%"
								>实名认证&nbsp;&nbsp;  未认证
							</p>
						</template>
					</uni-list-item> -->
					<uni-list-item
						v-if="userWallet.isPtSystemUser"
						:clickable="true"
						@tap="goBackEnd('pt')"
						title="进入平台"
						showArrow
						:border="false"
					>
						<template v-slot:body>
							<p style="width: 100%"
								>{{$t('setting.enter_platform')}}
							</p>
						</template>
					</uni-list-item>
					<uni-list-item
						v-if="userWallet.isShSystemUser"
						:clickable="true"
						@tap="goBackEnd('sh')"
						title="进入商家后台"
						showArrow
						:border="false"
					>
						<template v-slot:body>
							<p style="width: 100%"
								>{{$t('setting.enter_merchant_backend')}}
							</p>
						</template>
					</uni-list-item>
					
					<uni-list-item
						v-if="isBetaUser()"
						:clickable="true"
						@tap="changeLanguage()"
						title="切换语言"
						showArrow
						:border="false"
					>
						<template v-slot:body>
							<p style="width: 100%"
								>{{currentLang === 'en' ? 'Switch to Chinese': '切换为英文'}}
							</p>
						</template>
					</uni-list-item>
					<uni-list-item
						title="我的二维码"
						clickable
						@tap="sheep.$router.go('/pages/user/qrcode-share')"
						:border="false"
					>
						<template v-slot:body>
							<p style="width: 100%; display: flex; align-items: center">
								{{$t('setting.enter_merchant_backend')}} &nbsp;&nbsp;&nbsp;&nbsp;
								<su-image
									class="content-img"
									style="border: 1px solid #f4f4f4"
									:current="0"
									:src="state.model?.avatar"
									:height="100"
									:width="100"
									:radius="0"
									mode="scaleToFill"
								/>
							</p>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</uni-forms>
		
		
		<!-- 当前社交平台的绑定关系，只处理 wechat 微信场景 -->
		<view v-if="sheep.$platform.name !== 'H5'">
			<view class="title-box ss-p-l-30">{{$t('setting.third_party_account_binding')}}</view>
			<view class="account-list ss-flex ss-row-between">
				<view v-if="'WechatOfficialAccount' === sheep.$platform.name" class="ss-flex ss-col-center">
					<image class="list-img" :src="sheep.$url.static('/static/images/WechatOfficialAccount.png')" />
					<text class="list-name">{{$t('setting.wechat_public_account')}}</text>
				</view>
				<view v-if="'WechatMiniProgram' === sheep.$platform.name" class="ss-flex ss-col-center">
					<image class="list-img" :src="sheep.$url.static('/static/images/WechatMiniProgram.png')" />
					<text class="list-name">{{$t('setting.wechat_mini_program')}}</text>
				</view>
				<view v-if="'App' === sheep.$platform.name" class="ss-flex ss-col-center">
					<image class="list-img" :src="sheep.$url.static('/static/images/wechat.png')" />
					<text class="list-name">{{$t('setting.wechat_open_platform')}}</text>
				</view>
				<view class="ss-flex ss-col-center">
					<view class="info ss-flex ss-col-center" v-if="state.thirdInfo">
						<image class="avatar ss-m-r-20" :src="sheep.$url.cdn(state.thirdInfo.avatar)" />
						<text class="name">{{ state.thirdInfo.nickname }}</text>
					</view>
					<view class="bind-box ss-m-l-20">
						<button v-if="state.thirdInfo.openid" class="ss-reset-button relieve-btn"
							@tap="unBindThirdOauth">
							{{ $t('setting.unbind') }}
						</button>
						<button v-else class="ss-reset-button bind-btn" @tap="bindThirdOauth">{{$t('setting.bind')}}</button>
					</view>
				</view>
			</view>
		</view>
		
		<su-fixed bottom placeholder>
			<view class="ss-p-x-20 ss-p-b-40">
				<button class="loginout-btn ss-reset-button" @tap="onLogout" v-if="isLogin">
					{{$t('user.log_out')}}
				</button>
			</view>
		</su-fixed>
		<!-- <su-fixed bottom placeholder bg="none">
			<view class="footer-box ss-p-20">
				<button class="ss-rest-button logout-btn ui-Shadow-Main" @tap="onSubmit">保存</button>
			</view>
		</su-fixed> -->
	</s-layout>
</template>

<script setup>
	import { computed, reactive, onBeforeMount } from 'vue';
	import sheep from '@/sheep';
	import { clone } from 'lodash';
	const isLogin = computed(() => sheep.$store('user').isLogin);
	import { showAuthModal, showShareModal } from '@/sheep/hooks/useModal';
	import FileApi from '@/sheep/api/infra/file';
	import UserApi from '@/sheep/api/member/user';
	import AuthUtil from '@/sheep/api/member/auth';
	import { isBetaUser } from '@/sheep/hooks/useApp.js'
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import { setLanguage } from '@/locale'
	import { useI18n } from 'vue-i18n';
	const { t } = useI18n();
	const userInfo = computed(() => sheep.$store('user').userInfo);
	const userWallet = computed(() => sheep.$store('user').userWallet);
	const alipayAccount = computed(() => {
		let account = userInfo.value.alipayAccount;
		if (!account) {
			return false;
		}
		// 手机号脱敏
		if (/^\d{11}$/.test(account)) { // 检查是否是11位数字的手机号
			return `${account.substring(0, 3)}****${account.substring(7)}`;
		} else if (/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(account)) {
			const atIndex = account.indexOf('@');
			// 邮箱用户名长度小于等于3位时，不脱敏
			if (atIndex <= 3) {
				return account;
			}
			const username = account.substring(0, Math.ceil(atIndex / 2)); // 取邮箱用户名的一半
			const domain = account.substring(atIndex); // 邮箱域名部分
			return `${username}***${domain}`;
		}
	})
	const bankAccount = computed(() => {
		let account = userInfo.value.bankAccount;
		if (!account) {
			return false;
		}
		if (account.length === 8) {
			return account.substring(0, 2) + '********' + account.substr(-2);
		} else {
			return account.substring(0, 4) + '******' + account.substr(-4);
		}
	
	})
	// 修改支付宝账号
	const onChangeAlipayAccount = () => {
		showAuthModal('alipayAccount');
	};
	// 修改银行卡号
	const onChangeBankAccount = () => {
		showAuthModal('bankAccount');
	};
	const state = reactive({
		model: {}, // 个人信息
		rules: {},
		thirdInfo: {}, // 社交用户的信息
	});

	const placeholderStyle = 'color:#BBBBBB;font-size:28rpx;line-height:normal';

	

	// 绑定第三方账号
	async function bindThirdOauth() {
		let result = await sheep.$platform.useProvider('wechat').bind();
		if (result) {
			await getUserInfo();
		}
	}
	
	// 解绑第三方账号
	function unBindThirdOauth() {
		uni.showModal({
			title: t('user.unbind_reminder'),
			content:t('rules.unbind_warning'),
			cancelText: t('common.cancel'),
			confirmText: t('common.confirm'),
			success: async function(res) {
				if (!res.confirm) {
					return;
				}
				const result = await sheep.$platform.useProvider('wechat').unbind(state.thirdInfo.openid);
				if (result) {
					await getUserInfo();
				}
			},
		});
	}

	// 保存信息
	async function onSubmit() {
		const { code } = await UserApi.updateUser({
			avatar: state.model.avatar,
			nickname: state.model.nickname,
			sex: state.model.sex,
		});
		if (code === 0) {
			await getUserInfo();
		}
	}

	// 获得用户信息
	const getUserInfo = async () => {
		// 个人信息
		const userInfo = await sheep.$store('user').getInfo();
		state.model = clone(userInfo);

		// 获得社交用户的信息
		if (sheep.$platform.name !== 'H5') {
			const result = await sheep.$platform.useProvider('wechat').getInfo();
			state.thirdInfo = result || {};
		}
	};
	// 退出账号
	function onLogout() {
		uni.showModal({
			title: t('setting.prompt'),
			content: t('setting.confirm_logout'),
			cancelText: t('common.cancel'),
			confirmText: t('common.confirm'),
			success: async function(res) {
				if (!res.confirm) {
					return;
				}
				const {
					code
				} = await AuthUtil.logout();
				if (code !== 0) {
					return;
				}
				sheep.$store('user').logout();
				uni.removeStorageSync('linkId');
				sheep.$router.go('/pages/index/user');
			},
		});
	}
	
	// 跳到平台到商户
	async function goBackEnd(type){
		const {
			code,
			data
		} = await AuthUtil.getConsumerRedirectUrl();
		if(code === 0){
			window.location.href = data;
		}
	}
	const currentLang = computed(() => {
		return uni.getStorageSync('userLanguage');
	});
	const changeLanguage = async () => {
		// setLanguage()
		
		console.log(currentLang.value)
		if(currentLang.value === 'en'){
			await UserApi.updateUser({language: 'zh-Hans'});
			setLanguage('zh-Hans');
		}else{
			await UserApi.updateUser({language: 'en'});
			setLanguage('en');
		}
	}


	onBeforeMount(() => {
		getUserInfo();
	});
	onLoad(()=>{
		uni.$on('alipayAccountChangeComplete', getUserInfo);
		uni.$on('bankAccountChangeComplete', getUserInfo);
	})
</script>

<style lang="scss" scoped>
	.loginout-btn {
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		color:#fff;
		width: 100%;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 30rpx;
	}
	:deep() {
		.uni-file-picker {
			border-radius: 50%;
		}

		.uni-list-chat__content-extra {
			display: flex;
			justify-content: center;
		}

		.uni-file-picker__container {
			margin: -14rpx -12rpx;
		}

		.file-picker__progress {
			height: 0 !important;
		}

		.uni-list-item__content-title {
			font-size: 32rpx !important;
			color: #333333 !important;
			line-height: normal !important;
		}

		.uni-icons {
			font-size: 40rpx !important;
		}

		.is-disabled {
			color: #333333;
		}
	}

	:deep(.disabled) {
		opacity: 1;
	}

	.uni-list-item {
		min-height: 100rpx;
	}

	.gender-name {
		font-size: 28rpx;
		font-weight: 500;
		line-height: normal;
		color: #333333;
	}

	.title-box {
		font-size: 28rpx;
		font-weight: 500;
		color: #666666;
		line-height: 60rpx;
	}

	.logout-btn {
		width: 710rpx;
		height: 80rpx;
		background: linear-gradient(90deg, #132b85, #193bb6);
		border-radius: 40rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: $white;
	}

	.radio-dark {
		filter: grayscale(100%);
		filter: gray;
		opacity: 0.4;
	}

	.content-img {
		border-radius: 50%;
	}

	.header-box-content {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		overflow: hidden;
		border-radius: 50%;
	}

	.avatar-action {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 0;
		z-index: 1;
		width: 160rpx;
		height: 46rpx;
		background: rgba(#000000, 0.3);

		.avatar-action-btn {
			width: 160rpx;
			height: 46rpx;
			font-weight: 500;
			font-size: 24rpx;
			color: #ffffff;
		}
	}

	// 绑定项
	.account-list {
		background-color: $white;
		height: 100rpx;
		padding: 0 20rpx;

		.list-img {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
		}

		.list-name {
			font-size: 28rpx;
			color: #333333;
		}

		.info {
			.avatar {
				width: 38rpx;
				height: 38rpx;
				border-radius: 50%;
				overflow: hidden;
			}

			.name {
				font-size: 28rpx;
				font-weight: 400;
				color: $dark-9;
			}
		}

		.bind-box {
			width: 100rpx;
			height: 50rpx;
			line-height: normal;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;

			.bind-btn {
				width: 100%;
				height: 100%;
				border-radius: 25rpx;
				background: #f4f4f4;
				color: #999999;
			}

			.relieve-btn {
				width: 100%;
				height: 100%;
				border-radius: 25rpx;
				background: var(--ui-BG-Main-opacity-1);
				color: var(--ui-BG-Main);
			}
		}
	}

	.list-border {
		font-size: 28rpx;
		font-weight: 400;
		color: #333333;
		border-bottom: 2rpx solid #eeeeee;
	}

	image {
		width: 100%;
		height: 100%;
	}
</style>
