<script setup lang="ts">
import Config from '@/config'
import {useUserStore} from '@/store'
import type chooseImageVue from '@/components/choose-image/choose-image.vue'
import { appUserEditUserInfoPost } from '@/service'
import {debounce} from 'throttle-debounce';
import {upload} from '@/utils/upload/alioss'
import {EventEnum} from "@/constant/enums";

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


const chooseImageRef = ref<InstanceType<typeof chooseImageVue> | null>(null)
const form = ref({
  avatar: userStore.userInfo?.avatar,
})


watch(
    () => userStore.userInfo,
    (newValue) => {
      console.log('userInfo', newValue)
      form.value = {
        avatar: newValue?.avatar || '',
      }
    },
    {
      deep: true,
    },
)

async function handleCropperAvatarSuccess(avatarUrl: string) {
  try {
    await uni.showLoading({
      title: t('common.prompt.up-cross'),
      mask: true,
    })
    const res = await upload(avatarUrl, '.png', 'app/avatar/')
    console.log('111111', res)
    form.value.avatar = res as string
  }finally {
    uni.hideLoading()
  }
}

// 编辑用户信息
async function submit() {
  try {
    await appUserEditUserInfoPost({
      body: {
        avatar: form.value.avatar,
      }
    })
    await uni.showToast({title: t('common.prompt.save-successfully'), icon: 'none'})
    await userStore.getUserInfo()
  } catch (e) {
  }
}

const handleSubmit = debounce(Config.debounceLongTime, submit, {atBegin: true})

function handleAddImg() {
  chooseImageRef.value?.init()
}

function handleChooseImageChange(event: string[]) {
  if (!Array.isArray(event)) {
    return
  }

  navigateTo(`/pages-user/pages/user-info/cropper-avatar?data=${encodeURIComponent(event[0])}`)
}

function handlePreviewImage() {
  chooseImageRef.value?.close()
  uni.previewImage({
    url: form.value.avatar,
    urls: [form.value.avatar as string],
  })
}


function navigateTo(url: string) {
  uni.navigateTo({url})
}

onLoad(async () => {
  uni.$on(EventEnum.CROPPER_AVATAR, handleCropperAvatarSuccess)
})

onUnload(() => {
  uni.$off(EventEnum.CROPPER_AVATAR, handleCropperAvatarSuccess)
})

onBackPress(() => {
  if (chooseImageRef.value?.show) {
    chooseImageRef.value.close()
    return true
  }
})
</script>

<template>
  <choose-image :isUpload="false" ref="chooseImageRef" @change="handleChooseImageChange">
    <template #top>
      <view class="p-[32rpx+20rpx] text-34rpx text-primary text-center font-bold" @click="handlePreviewImage">
        <text>{{ t('pages-user.user-info.view-larger-image') }}</text>
      </view>
    </template>
  </choose-image>
  <view class="h-full flex flex-col">
    <navbar :title="t('navbar-personal-information')"/>
    <view class="bg-#fff">
      <view class="p-18rpx flex items-center justify-between border-bottom">
        <view class="shrink-0 mr-20rpx text-30rpx text-primary">{{ t('pages-user.user-info.head-portrait') }}</view>
        <view class="flex items-center" @click="handleAddImg">
          <image :src="form.avatar" class="shrink-0 w-80rpx h-80rpx rounded-full"></image>
          <image
            src="@img/chef/100202.png"
            class="shrink-0 ml-16rpx w-22rpx h-30rpx"
        ></image>
        </view>
      </view>
      <view class="px-18rpx py-37rpx flex items-center justify-between"
            @click="navigateTo('/pages-user/pages/edit-nickname/index')">
        <view class="shrink-0 mr-20rpx text-30rpx text-primary">{{ t('pages-user.user-info.nickname') }}</view>
        <view class="flex-1 flex items-center justify-end text-30rpx text-primary">
          <text>{{ `${userStore.userInfo.firstName} ${userStore.userInfo.surname}` }}</text>
          <image
            src="@img/chef/100202.png"
            class="shrink-0 ml-16rpx w-22rpx h-30rpx"
        ></image>
        </view>
      </view>
    </view>


    <view class="mt-318rpx px-30rpx">
          <wd-button custom-class="!h-108rpx !text-36rpx font-bold !rounded-16rpx" block @click="handleSubmit">
            {{ t('common.save') }}
          </wd-button>
        </view>
  </view>
</template>

<style scoped lang="scss">
:deep(.wd-picker-view-column__item--active) {
  font-weight: bold;
}
</style>
