<template>
  <view class="image-uploader">
    <!-- 已上传图片列表 -->
    <view class="flex flex-wrap gap-2">
      <view 
        v-for="(url, index) in modelValue" 
        :key="index" 
        class="relative w-20 h-20 rounded-lg overflow-hidden border border-gray-200"
      >
        <image 
          :src="url" 
          class="w-full h-full object-cover" 
          mode="aspectFill"
          @click="previewImage(index)"
        />
        <view 
          class="absolute top-0 right-0 w-5 h-5 bg-red-500 rounded-full flex items-center justify-center -mt-1 -mr-1 z-10"
          @click="removeImage(index)"
        >
          <text class="uni-icons uniui-close text-white text-xs"></text>
        </view>
      </view>
      
      <!-- 上传按钮 -->
      <view 
        v-if="modelValue.length < maxCount"
        class="w-20 h-20 rounded-lg border-2 border-dashed border-gray-300 flex flex-col items-center justify-center cursor-pointer bg-gray-50"
        @click="chooseImage"
      >
        <text class="uni-icons uniui-camera-filled text-gray-400 text-xl"></text>
        <text class="text-xs text-gray-400 mt-1">{{ modelValue.length }}/{{ maxCount }}</text>
      </view>
    </view>
    
    <!-- 提示文字 -->
    <text v-if="tip" class="text-xs text-gray-400 mt-2 block">{{ tip }}</text>
  </view>
</template>

<script setup lang="ts">
interface Props {
  modelValue: string[]
  maxCount?: number
  tip?: string
}

const props = withDefaults(defineProps<Props>(), {
  maxCount: 9,
  tip: '',
})

const emit = defineEmits<{
  'update:modelValue': [value: string[]]
}>()

function chooseImage() {
  const remainCount = props.maxCount - props.modelValue.length
  if (remainCount <= 0) {
    uni.showToast({ title: '最多上传' + props.maxCount + '张', icon: 'none' })
    return
  }

  uni.chooseImage({
    count: remainCount,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const newImages = [...props.modelValue, ...res.tempFilePaths]
      emit('update:modelValue', newImages)
    },
  })
}

function removeImage(index: number) {
  const newImages = [...props.modelValue]
  newImages.splice(index, 1)
  emit('update:modelValue', newImages)
}

function previewImage(index: number) {
  uni.previewImage({
    urls: props.modelValue,
    current: props.modelValue[index],
  })
}
</script>
