<template>
  <template v-if="type === 'avatar'">
    <van-image v-if="url" round class="avatar" fit="cover" :src="signed_url" />
    <van-icon class="avatar" v-else size="25" name="https://b.yzcdn.cn/vant/icon-demo-1126.png" />
  </template>
  <template v-else>
    <van-image @click="preview(signed_url)" :radius="radius" v-if="signed_url" width="100%" height="auto" fit="contain" :src="signed_url" />
    <van-empty v-else-if="valid(task)" description="图片处理中..."></van-empty>
    <van-empty image="error" v-else description="图片处理失败" />
  </template>
</template>
<script lang="ts">
import {defineComponent} from 'vue'
import {computedAsync} from '@vueuse/core'
import {Empty, Icon, Image, showImagePreview} from 'vant'
import {UpyunAccess} from '~/utils/upyun'
import {CommonTask, TaskStatuses} from "~/types";

export default defineComponent({
  name: "hty-image",
  components: {
    [Image.name]: Image,
    [Empty.name]: Empty,
    [Icon.name]: Icon
  },
  props: ['url', 'task', 'radius', 'type'],
  setup(props) {

    const preview = (url: string) => {
      showImagePreview([url])
    }

    const valid = (task: CommonTask) => task.task_id && /\w{8}(-\w{4}){3}-\w{12}/.test(task.task_id) && task.task_status !== TaskStatuses.FAILED

    const signed_url = computedAsync(async () => {
      if (props.url?.includes("upyun")) {
        return (await UpyunAccess.getSign(props.url));
      }
      return props.url
    });

    return { preview, valid, signed_url }
  }
});
</script>

<style scoped lang="less">
.avatar{
  width: 0.5rem;
  height: 0.5rem;
  margin-right: 0.1rem;
}
</style>
