// 头像 列表
<template>
	<div :class="style['avatar-wrapper']" :style="isShow ? 'height:160px' : ''">
		<div :class="style['avatar-select-wrapper']">
			<!-- 头像列表中的头像 assets -->
			<svg
				v-if="avatarNameValue"
				:class="style['svg-icon-select']"
				aria-hidden="true"
			>
				<use :xlink:href="`#icon-${avatarNameValue}`" />
			</svg>
			<!-- 默认头像 -->
			<img
				v-else
				:class="style['avatar-default']"
				src="~@/assets/svg/default-avatar.svg"
			/>
		</div>

		<!-- 头像列表 -->
		<template v-if="!isShow">
			<div :class="style['avatar-wrapper-btn']">
				<a-button type="primary" @click="showDrawer">修改头像</a-button>
			</div>
			<a-drawer
				placement="right"
				:closable="true"
				:visible="visible"
				:get-container="false"
				:wrap-style="{ position: 'absolute' }"
				@close="onClose"
			>
				<a-radio-group
					v-model:value="avatarNameValue"
					@change="onAvatarChange"
				>
					<a-radio
						v-for="(_item, i) in avatarArr"
						:key="i"
						:value="`avatar${i}`"
					>
						<p :class="style['avatar-wrapper-item']">
							<svg :class="style['svg-icon']" aria-hidden="true">
								<use :xlink:href="`#icon-avatar${i}`" />
							</svg>
						</p>
					</a-radio>
				</a-radio-group>
			</a-drawer>
		</template>
	</div>
</template>
<script lang="ts">
import style from './index.module.less'
import { defineComponent, onMounted, ref, watch } from 'vue'
export default defineComponent({
	components: {},
	props: {
		// 头像文件名称
		avatarName: {
			type: String,
			required: false,
			default: '',
		},
		// 只展示，不可编辑
		isShow: {
			type: Boolean,
			required: false,
			default: false,
		},
	},
	emits: ['on-avatar-confirm'],
	setup(props, context) {
		let avatarArr = new Array(51).fill('avatar')
		const avatarNameValue = ref<string>('')

		const visible = ref(true)

		const showDrawer = () => {
			visible.value = true
		}

		const onClose = () => {
			visible.value = false
		}

		const onAvatarChange = e => {
			visible.value = false
			avatarNameValue.value = e.target.value
			context.emit('on-avatar-confirm', e.target.value)
		}

		watch(
			() => props.avatarName,
			newVal => {
				let pattern = new RegExp(/^avatar[0-9]+$/g)
				if (pattern.test(newVal)) {
					avatarNameValue.value = newVal
				} else {
					avatarNameValue.value = ''
				}
			},
			{ deep: true, immediate: true }
		)

		onMounted(() => {
			visible.value = false
		})

		return {
			style,
			avatarArr,
			avatarNameValue,
			visible,
			showDrawer,
			onClose,
			onAvatarChange,
		}
	},
})
</script>
