<template>
  <div class="w-full h-[100vh] bg-white">
    <ChatHeaderBar title="设置当前聊天背景"></ChatHeaderBar>
    <div class="pt-50">
      <van-cell clickable @click="open" size="large" title="从相册中选择" is-link></van-cell>
      <van-cell clickable @click="changeGroupBg" size="large" title="设置成默认背景"></van-cell>
    </div>
  </div>
</template>
<script setup>
const route = useRoute()

definePageMeta({
  layout: false
})

useSeoMeta({
  title: '我的消息'
})

const { open, onChange } = useFileDialog({
  accept: '.png,.png,.jpeg,.JPG,Png '
})

const bgImage = ref('')

onChange(async (files) => {
  if (!files.length) return

  const formData = new FormData()
  formData.append('uploadFile', files[0])
  formData.append('asImage', true)
  formData.append('fieldName', 'image')
  const maxSize = 20 * 1024 * 1024 // 20 MB
  if (files[0].size > maxSize) {
    showToast('上传图片过大，请重新上传')
    return
  } else {
    try {
      showLoadingToast({
        message: '图片上传中...',
        duration: 1000000
      })

      const { data } = await request('/website/tourMessage/upload', {
        method: 'post',
        body: formData
      })
      bgImage.value = data.fileUrl
      changeGroupBg()
      closeToast()
    } catch (error) {
      closeToast()
      showToast('图片上传失败')
    }
  }
})

// 修改背景图
const changeGroupBg = async () => {
  try {
    const res = await request('/website/tourMember/updateSingleTourMember', {
      method: 'post',
      body: {
        groupId: route.query.groupId,
        groupBackImage: bgImage.value
      }
    })

    if (res && res?.success) {
      navigateTo({
        path: 'chat/group',
        query: route.query.groupId,
        replace: true
      })
      showSuccessToast('聊天背景设置成功')
    }
    // else {
    //   showFailToast('聊天背景设置失败')
    // }
  } catch (error) {}
}
</script>
<style lang="scss" scoped></style>
