<template>
    <!--    上传参考图    -->
    <view
        class="uploader mt-[30rpx] flex justify-center items-center"
        @click="onUploader"
    >
        <!--    没有图片的时候    -->
        <view
            v-if="!modelValue"
            class="flex flex-col justify-center items-center"
        >
            <image
                class="w-[72rpx] h-[72rpx] mb-[12rpx]"
                src="@/packages/static/images/draw_upload.png"
            ></image>
            <view class="text-muted">点击上传参考图</view>
        </view>
        <!--    有图片的时候    -->
        <view
            v-else
            class="w-full h-full relative text-center has_image"
            @click.stop
        >
            <image
                class="has_img_delete w-[42rpx] h-[42rpx]"
                src="@/packages/static/images/delete.png"
                @click.stop="emit('update:modelValue', '')"
            ></image>
            <image
                class="w-full h-full"
                :src="modelValue"
                mode="aspectFit"
            ></image>
        </view>
    </view>
</template>

<script setup lang="ts">
import { uploadImage } from '@/api/app'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'

const appStore = useAppStore()

const emit = defineEmits<{
    (event: 'update:modelValue', value: string): void
}>()
const props = withDefaults(
    defineProps<{
        modelValue?: any
    }>(),
    {
        modelValue: ''
    }
)

const onUploader = () => {
    const userStore = useUserStore()
    if (!userStore.isLogin) {
        return uni.navigateTo({ url: '/pages/login/login' })
    }
    uni.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: (res) => {
            const img_lmit = appStore.getDrawConfig.img_limit
            if (res?.tempFiles[0].size >= img_lmit * 1024 * 1024) {
                uni.$u.toast(`请上传${img_lmit}MB以下的图片`)
                return new Error('文件超出大小～')
            }
            uploadImg(res.tempFilePaths[0])
        }
    })
}

const uploadImg = async (file: string) => {
    uni.showLoading({
        title: '上传中'
    })
    try {
        const res: any = await uploadImage(file, { type: 'draw' })
        emit('update:modelValue', res.path)
        uni.hideLoading()
    } catch (error) {
        uni.hideLoading()
        uni.$u.toast(error)
        console.log('上传图片失败', error)
    }
}
</script>

<style lang="scss" scoped>
.uploader {
    height: 200rpx;
    border-radius: 8rpx;
    border: 1px dashed #dcdfe6;
    @apply bg-page-base;
    .has_img_delete {
        position: absolute;
        right: 20rpx;
        top: 20rpx;
        z-index: 10;
    }
}
</style>
