<script lang="ts" setup>
import {uploadToS3} from '@/utils/upload/ymx'

const props = withDefaults(
    defineProps<{
      count?: number
      isUpload?: boolean
    }>(),
    {
      count: 1,
      isUpload: true,
    },
)

const emits = defineEmits(['change', 'update:modelValue'])

const {t} = useI18n()

const show = ref(false)

function init() {
  show.value = true
}

function close() {
  show.value = false
}

// 选择图片
function handleChooseImage(type: 'album' | 'camera') {
  close()


  chooseImage(type)
}

function chooseImage(type: 'album' | 'camera') {
  // #ifdef APP-PLUS
  uni.chooseMedia({
    count: props.count,
    mediaType: ['image'],
    sourceType: type === 'album' ? ['album'] : ['camera'],
    maxDuration: 30,
    camera: 'back',
    async success(res) {
      let files: string | string[] = []
      const asyncList = []
      console.log('res.tempFiles', res.tempFiles)
      if (res.tempFiles.length === 0) return
      files = res.tempFiles.map((item) => item.tempFilePath)
      if (props.count > 0) {
        // 根据count截取数组长度
        files = files.slice(0, props.count)
      }
      if (!props.isUpload) {
        return emits('change', files)
      }
      await uni.showLoading({
        title: t('common.loading') + '...',
        mask: true,
      })
      for (let i = 0; i < files.length; i++) {
        // asyncList.push(upload(files[i]))
        asyncList.push(uploadToS3(files[i]))
        console.log(asyncList)
      }
      Promise.all(asyncList)
          .then((results) => {
            console.log(results)
            emits('change', results)
          })
          .finally(() => {
            uni.hideLoading()
          })
    }
  })
  // #endif
}


defineExpose({
  show,
  init,
  close,
})
</script>

<template>
  <view>
    <wd-popup v-model="show" custom-style="border-radius: 30rpx 30rpx 0 0;" position="bottom" safe-area-inset-bottom
              @close="close">
      <slot name="top"></slot>
      <view class="p-[32rpx+20rpx] text-34rpx text-primary text-center font-bold" @click="handleChooseImage('album')">
        <text>{{ t('common.select-from-album') }}</text>
      </view>
      <view class="p-[32rpx+20rpx] text-34rpx text-primary text-center font-bold" @click="handleChooseImage('camera')">
        <text>{{ t('common.photograph') }}</text>
      </view>
      <view class="h-20rpx bg-common"></view>
      <view class="p-[32rpx+20rpx] text-34rpx text-primary text-center" @click="close">{{ t('common.cancel') }}</view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped></style>
