<template>
  <view class="photo-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="previewMedia(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="removeMedia(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 bg-gray-50"
        @click="chooseMedia"
      >
        <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">
const props = withDefaults(
  defineProps<{
    modelValue: string[]
    maxCount?: number
    tip?: string
    mediaType?: ('image' | 'video')[]
  }>(),
  {
    maxCount: 9,
    tip: '',
    mediaType: () => ['image', 'video']
  }
)

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

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

  uni.chooseMedia({
    count: remainCount,
    mediaType: props.mediaType,
    sourceType: ['album', 'camera'],
    success: (res) => {
      const paths = res.tempFiles.map(f => f.tempFilePath)
      emit('update:modelValue', [...props.modelValue, ...paths])
    }
  })
}

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

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