<template>
	<view class="change-language">
		<!-- 选择语言弹出框 -->
		<u-popup :show="show" mode="bottom" @close="$emit('close');$play()">
			<view class="language-list">
				<view v-for="item in languageList" :key="item.key" class="language" :class="{ activeLanguage : currentLanguageKey === item.key}" @click="select(item)">{{ item.name }}</view>
			</view>
			<view class="language-btns">
				<view @click="$emit('close');$play()" class="btn">{{ $t('page.changeLanguage.cancel') }}</view>
				<view @click="changeLanguage(currentLanguage)" class="btn">{{ $t('page.changeLanguage.confirm') }}</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data(){
			return {
				languageList: [
					{
						name:'English',
						key : "en"
					},
					{
						name:'español',
						key : "es"
					}
				],
				currentLanguage : {},
				currentLanguageKey : this.$i18n.locale
			}
		},
		props : {
			show : {
				type : Boolean,
				default : false
			}
		},
		methods : {
			//选择语言
			select(item){
				this.$play()
				this.currentLanguage = item;
				this.currentLanguageKey = item.key
			},
			
			//修改当前语言
			changeLanguage(res){
				this.$play()
				//#ifdef  H5
				this.$router.go(0); //刷新页面，不然validate.js不好国际化
				//#endif
				//#ifdef  APP-PLUS
				uni.navigateTo({
					url: '/pages/home/home' // 要刷新的页面路径
				});
				//#endif
				
				if(!res.key){
					return
				}
				
				this.curLanguage = res.key;
				// this.$store.commit('changeLanguage', res.key.code);
				uni.setStorage({
					key: 'language',
					data: res.key
				})
				this.$i18n.locale = res.key
				uni.setLocale(res.key) //切换语言环境必须在this.$i18n.locale之后，否则app端会有意想不到的bug
				this.$emit('close')
				
				uni.$resMessage = this.$t('message')
			}
		}
	}
</script>

<style lang="scss" scoped>
	.change-language{
		.language-list{
			border: 1px solid #ccc;
			width: 96%;
			margin: 0rpx auto 20rpx auto;
			
			.language{
				position: relative;
				display: flex;
				justify-content: center;
				align-items: center;
				color: $uni-text-color;
				height: 100rpx;
				border-bottom: 1px solid #ccc;
				font-size: 32rpx;
				
				&:last-child{
					border: none;
				}
			}
			
			.activeLanguage{
				&::after{
					position: absolute;
					top: 50%;
					right: 20rpx;
					content: "";
					width: 30rpx;
					height: 30rpx;
					border-radius: 50%;
					box-shadow: 0rpx 0rpx 30rpx $uni-bg-color-app;
					background: $uni-bg-color-app;
					transform: translateY(-50%);
				}
			}
		}
		
		.language-btns{
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			color: $uni-text-color;
			width: 96%;
			margin: 0rpx auto 20rpx auto;
			
			.btn{
				display: flex;
				align-items: center;
				justify-content: center;
				width: calc(50% - 15rpx);
				border: 1px solid #ccc;
				height: 80rpx;
			}
		}
	}
</style>