<template>
    <template v-if="preview">
        <view class="ut-image p-rtv ov-hd" @click.stop="previewImg" :style="{ width, height, borderRadius, backgroundColor: bgColor }">
            <up-image :src="thumbnailUrl" :mode="mode" :width="width" :height="height" :showLoading="false" :lazyLoad="lazyLoad"></up-image>
            <view v-if="title" class="ut-iamge-title">{{ title }}</view>
        </view>
    </template>
    <template v-else>
        <view class="ut-image p-rtv ov-hd" :style="{ width, height, borderRadius, backgroundColor: bgColor }">
            <up-image :src="thumbnailUrl" :mode="mode" :width="width" :height="height" :showLoading="false" :lazyLoad="lazyLoad"></up-image>
            <view class="ut-iamge-title" :style="{ fontSize: titleSize }">{{ title }}</view>
        </view>
    </template>
</template>

<script setup lang="ts" name="ut-image">
interface UtImageProps {
    width?: string;
    height?: string;
    value?: string;
    src?: string;
    url?: string;
    defaultSrc?: string; // 无图片时的默认图片
    preview?: boolean;
    borderRadius?: string;
    lazyLoad?: boolean;
    factor?: number; // 缩略图系数
    t?: string; // 缩略图质量/类型
    enableThumbnail?: boolean;
    mode?: any;
    bgColor?: string;
    title?: string;
    titleSize?: string;
}

const props = withDefaults(defineProps<UtImageProps>(), {
    width: '200rpx',
    height: '200rpx',
    value: '',
    src: '',
    url: '',
    defaultSrc: 'https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/common/avatar.png',
    preview: false,
    borderRadius: '16rpx',
    lazyLoad: true,
    factor: 4,
    t: '0',
    enableThumbnail: true,
    mode: 'aspectFit',
    bgColor: '#f7f7f7',
    title: '',
    titleSize: '28rpx',
});

// 将 value/src/url 统一为图片地址（按优先级：value > src > url > defaultSrc）
const imageUrl = computed<string>(() => props.value || props.src || props.url || props.defaultSrc || '');

// 生成缩略图URL（基于统一后的 imageUrl）
const thumbnailUrl = computed<string>(() => {
    const base = imageUrl.value;
    if (!base) return '';
    if (!props.enableThumbnail) return base;

    const w = Math.round(uni.upx2px(parseFloat(props.width)) * props.factor);
    const h = Math.round(uni.upx2px(parseFloat(props.height)) * props.factor);
    const separator = base.includes('?') ? '&' : '?';
    return `${base}${separator}w=${w}&h=${h}&t=${props.t}`;
});

// 获取原图URL
const getOriginalUrl = (): string => {
    const base = imageUrl.value;
    if (!base) return '';
    return base.split('?')[0];
};

// 预览图片（使用原图）
const previewImg = (): void => {
    if (!props.preview) return;
    const originalUrl = getOriginalUrl();
    if (!originalUrl) return;
    uni.previewImage({ urls: [originalUrl] });
};
</script>

<style lang="scss" scoped>
.ut-image {
    overflow: hidden;
}
.ut-iamge-title {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    font-size: 28rpx;
    color: #fff;
    text-align: center;
    background-color: rgba(0, 0, 0, 0.6);
}
</style>
