<template>
	<div class="page_container !bg-white">
		<NavBar :title="title">
			<div class="btn" :disabled="!value && !friendInfo" @click="saveChange">{{
        t('buttons.save')
      }}</div>
		</NavBar>
		<div class="mx-2">
			<div class="rounded-lg ">
				<van-field class="boderb1" v-model="value" :maxlength="16" label=""
					:placeholder="$t('placeholder.pleaseInput')"></van-field>
			</div>
		</div>
		<div class="tips">
			好名字可以让你的朋友更容易记住你。
		</div>
	</div>
</template>

<script setup lang="ts">
	import NavBar from '@/components/NavBar/index.vue'
	import { updateBusinessInfo } from '@/api/user'
	import useUserStore from '@/store/modules/user'
	import { feedbackToast } from '@/utils/common'
	import { IMSDK } from '@/utils/imCommon'
	import type { FriendUserItem } from 'open-im-sdk-wasm/lib/types/entity'

	const props = defineProps<{ friendInfo ?: FriendUserItem }>()

	const { t } = useI18n()
	const userStore = useUserStore()
	const router = useRouter()

	const value = ref(
		props.friendInfo ? props.friendInfo?.remark : userStore.storeSelfInfo.nickname,
	)
	const title = props.friendInfo ? t('remark') : t('updateNickName')

	const saveChange = () => {
		let func
		if (props.friendInfo) {
			func = IMSDK.setFriendRemark({
				toUserID: props.friendInfo.userID,
				remark: value.value,
			})
		} else {
			func = updateBusinessInfo({
				nickname: value.value,
				userID: userStore.storeSelfInfo.userID,
			})
		}
		func
			.then(() => {
				userStore.getSelfInfoFromReq()
				feedbackToast({ message: t('messageTip.nomalSuccess'), onClose: router.back })
			})
			.catch((error) => feedbackToast({ message: t('messageTip.nomalFailed'), error }))
	}
</script>

<style lang="scss" scoped>
	.boderb1 {
		border-bottom: 1px solid #D8D8D8;
		font-size: 0.97rem;
		color: #171717;
		margin-top: 1rem;
	}

	.tips {
		font-size: 0.78rem;
		color: #A5A5A5;
		padding: 0.84rem 1.3rem;
	}

	.btn {
		width: 3.64rem;
		height: 1.95rem;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 0.8rem;
		color: #fff;
		background-color: #07C160;
		border-radius: 0.2rem;
	}
</style>