<template>
	<view v-if="canSwitch">
		<view
			class="switch-row"
			hover-class="switch-row-hover"
			:hover-stay-time="100"
			@tap.stop="openSwitch"
		>
			<text class="switch-label">切换账号</text>
			<u-icon name="arrow-right" color="#C9CDD4" size="28" />
		</view>
		<account-switch-panel
			ref="accountSwitchPanel"
			mode="switch"
			@switched="onSwitched"
		/>
	</view>
</template>

<script>
import AccountSwitchPanel from '@/components/account-switch/account-switch-panel.vue';
import { getDoctorWxSiblingAccounts } from '@/api/doctorAuth.js';
import {
	saveLoginSession,
	fetchProfileAfterLogin,
	navigateAfterLogin,
} from '@/utils/loginSession.js';

export default {
	name: 'AccountSwitchEntry',
	components: { AccountSwitchPanel },
	data() {
		return {
			canSwitch: false,
		};
	},
	mounted() {
		this.checkAccounts();
	},
	methods: {
		checkAccounts() {
			getDoctorWxSiblingAccounts()
				.then((wrap) => {
					if (wrap && wrap.ok) {
						this.canSwitch = (wrap.data || []).length > 1;
					}
				})
				.catch(() => {
					this.canSwitch = false;
				});
		},
		openSwitch() {
			this.$refs.accountSwitchPanel.open();
		},
		async onSwitched(result) {
			saveLoginSession(result);
			await fetchProfileAfterLogin(result);
			this.$toast('切换成功');
			setTimeout(() => {
				navigateAfterLogin(result);
			}, 400);
		},
	},
};
</script>

<style lang="scss" scoped>
.switch-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 36rpx 0;
	border-bottom: 1rpx solid #f2f3f5;
}

.switch-row-hover {
	background: #f7f8fa;
}

.switch-label {
	font-size: 30rpx;
	color: #31353d;
}
</style>
