<template>
  <FlexRow justify="space-between">
    <Image 
      v-for="index of 3" 
      :key="index" 
      :src="images[index - 1]" 
      radius="radius.md"
      :width="200"
      :height="140"
      mode="aspectFill"
      defaultImage=""
      touchable
    >
      <template #empty>
        <Touchable
          direction="column" 
          position="absolute" 
          inset="0" 
          center
          backgroundColor="background.primary"
          @click="uploadImage(index)"
        >
          <Icon name="add" size="fontSize.md" />
          <Text text="上传封面" fontConfig="secondText" />
        </Touchable>
      </template>
      <!-- <FlexCol 
        v-if="index === 3 && images.length >= 3" 
        position="absolute" inset="0" 
        center 
        backgroundColor="mask.default"
      >
        <Text :text="`更多相册`" fontSize="fontSize.lg" color="white" />
      </FlexCol> -->
    </Image>
  </FlexRow>

</template>

<script setup lang="ts">
import FlexRow from '@/components/layout/FlexRow.vue';
import Image from '@/components/basic/Image.vue';
import Touchable from '@/components/feedback/Touchable.vue';
import Icon from '@/components/basic/Icon.vue';
import Text from '@/components/basic/Text.vue';
import CommonContent from '@/api/CommonContent';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { toast } from '@/components/utils/DialogAction';
import LightVillageApi from '@/api/light/LightVillageApi';
import { computed } from 'vue';

const props = withDefaults(defineProps<{
  villageId: number;
  images?: string[];
}>(), {
  images: () => [],
});
const emit = defineEmits<{
  (e: 'update:images', images: string[]): void;
}>();

const images = computed(() => {
  return props.images.map(image => {
    if (image === 'https://xycdn.wenlvti.net')
      return '';
    return image
  });
});

async function uploadImage(index: number) {
  const tempFilePath = await new Promise<string>((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        resolve(res.tempFilePaths[0]);
      },
    });
  });

  try {
    const image = await CommonContent.uploadImages(tempFilePath);
    if (image) {
      if (props.images.length >= index)
        props.images[index - 1] = image;
      else
        props.images.push(image);
    }
    toast('上传成功');
    await LightVillageApi.updateVillageGallery(props.villageId, props.images);
    emit('update:images', props.images);
  } catch (error) {
    showError(error);
  }
}
</script>