<template>
	<view class="f-straight wrapper">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" validateTrigger="bind" label-width="105px" label-align="right">
			<uni-forms-item label="头像" name="avatar" class="f-straight" required>
        <view style="display: flex;flex-wrap: wrap;">
          <view class="upload-img" v-if="formData?.avatar">
            <uni-icons size="35" type="clear" color="#fe574a" style="position: absolute;right: -15px; top: -15px; z-index: 9" @click="formData.avatar = ''"></uni-icons>
            <image :src="formData?.avatar" mode="contain" style="width: 200rpx;height: 200rpx;" @click="handlePreviewImage"></image>
          </view>
          <view v-else class="upload-file" @click="uploadPhotos">
            <uni-icons type="plusempty" size="50" color="#f1f1f1"></uni-icons>
          </view>
        </view>
			</uni-forms-item>
		</uni-forms>
	</view>
</template>

<script setup>
import { pathToBase64 } from '@/utils/image-tools.js'
import { ref, watch } from 'vue'
const props = defineProps({
  data: {
    type: String,
    default: ''
  }
})

const form = ref()
const formData = ref({ avatar:'' })

watch(
  () => props.data,
  (newVal) => {
    formData.value.avatar = newVal
  },
  { immediate: true },
)

// 图片预览
const handlePreviewImage = () => {
  uni.previewImage({
    current: 0,
    urls: [formData.value.avatar]
  })
}

// 选择头像
const uploadPhotos = () => {
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    async success(res) {
      console.log('res:', res)
      const size = res.tempFiles[0]?.size || 0
      if (size >= 31457280) {
        uni.showToast({
          icon: 'none',
          title: '头像上传大小不得超过 20MB !',
          duration: 2000
        })
        return
      }
      // 选取图片并转为base64
      formData.value.avatar = await pathToBase64(res.tempFilePaths[0])
    }
  })
}

const rules = {
	avatar:{
		rules: [{required: true, errorMessage: '请上传头像' }]
	}
}

// const submit = async () => {
//   const valid = await unref(form).validate()
//   if (!valid) return
// }

</script>

<style lang="less" scoped>

.wrapper{
	padding: 15px;
  padding-top: 30px;
}
.upload-img{
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border: 1px solid #f1f1f1;
  margin: 10rpx;
}
.upload-file{
  width: 200rpx;
  height: 200rpx;
  border: 1px solid #f1f1f1;
  margin: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10rpx;
}
</style>