<template>
  <view class="my-image-uploader" :class="{ disabled: props.disabled }">
    <view class="img-list">
      <image v-for="(item, index) in fileList" :key="index" :src="item" class="img" mode="aspectFill"
        @click="chooseImage" />
    </view>
    <view class="upload-btn" v-if="fileList.length < maxCount" @click="chooseImage">
      <u-icon name="plus" size="40" color="#c0c4cc"></u-icon>
    </view>

    <CameraUpload ref="cameraUploadRef" @confirm="onCameraConfirm" />
  </view>
</template>
<script setup>
import { ref } from 'vue'
import { $upload, Toast } from '@/utils'
import { t } from "@/locale"
import CameraUpload from "./CameraUpload.vue";

const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  maxCount: { type: Number, default: 1 },
  disabled: {
    type: Boolean,
    default: false
  },
})
const emit = defineEmits(['update:modelValue', 'success', 'delete', 'error'])

const fileList = ref([...props.modelValue])

const cameraUploadRef = ref(null)
const chooseImage = () => {
  if (props.disabled) return;
  cameraUploadRef.value && cameraUploadRef.value.open()
}

const onCameraConfirm = async (url) => {
  try {
    fileList.value = [];
    fileList.value.push(url)
    emit('update:modelValue', fileList.value)
    emit('success', url)
  } catch (error) {
    Toast.error(t('上传失败'))
    emit('error', error)
  }
}
</script>
<style lang="less" scoped>
.my-image-uploader {
  display: flex;
  flex-wrap: wrap;

  &.disabled {
    opacity: 0.5;
    pointer-events: none;
  }

  .img-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;

    .img {
      width: 150rpx;
      height: 150rpx;
      border-radius: 8rpx;
      background: #f5f7fa;
    }
  }

  .upload-btn {
    width: 150rpx;
    height: 150rpx;
    border: 1px dashed #c0c4cc;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
  }
}
</style>