<template>
    <view class="upload-image">
        <view class="image-list">
            <view v-for="(image, index) in imageUrls" :key="index" class="image-item">
                <image class="image" :src="image" mode="aspectFill" @click="handlePreview(index)"></image>
                <view class="image-delete" @click="handleDelete(index)">
                    <image class="delete-icon" src="/static/images/common/3.png" mode="aspectFit"></image>
                </view>
            </view>

            <!-- 上传按钮 -->
            <view v-if="imageList.length < maxCount && !uploading" class="upload-box" @click="handleChooseImage">
                <text class="upload-icon">+</text>
                <text class="upload-text">上传图片</text>
            </view>

            <!-- 上传中 -->
            <view v-if="uploading" class="upload-box uploading">
                <text class="upload-text">上传中...</text>
            </view>
        </view>
    </view>
</template>

<script setup lang="uts">
    import { ref, computed } from 'vue'
    import { uploadImage } from '../../api/upload/image'
    import type { UploadResponse } from '../../types/workbench'

    // Props
    type Props = {
        modelValue?: UploadResponse[]
        maxCount?: number
        maxSize?: number // MB
        businessType?: string
    }
	
	let cameraInput: HTMLInputElement | null = null
	const createNativeInput = () => {
		if (cameraInput) return cameraInput
		// 创建原生 input 元素
		cameraInput = document.createElement('input')
		cameraInput.type = 'file'
		cameraInput.accept = 'image/*'
		cameraInput.style.position = 'fixed'
		cameraInput.style.top = '-1000px'
		cameraInput.style.left = '-1000px'
		cameraInput.style.opacity = '0'
		cameraInput.style.pointerEvents = 'none'
		cameraInput.setAttribute('capture', 'camera')
		// 添加到 body
		document.body.appendChild(cameraInput)
		return cameraInput
	}

    const props = withDefaults(defineProps<Props>(), {
        modelValue: () => [],
        maxCount: 9,
        maxSize: 50,
        businessType: 'image'
    })

    // Emits
    const emit = defineEmits<{
        (e: 'update:modelValue', images: UploadResponse[]): void
        (e: 'change', images: UploadResponse[]): void
    }>()

    // 图片列表
    const imageList = ref<UploadResponse[]>(props.modelValue)
    const uploading = ref<boolean>(false)
    
    // 计算图片 URL 数组（用于显示和预览）
    const imageUrls = computed<string[]>(() => {
        const urls: string[] = []
        for (let i = 0; i < imageList.value.length; i++) {
            urls.push(imageList.value[i].url)
        }
        return urls
    })

    // 上传图片
    const handleUpload = async (filePaths: string[]): Promise<void> => {
        try {
            uploading.value = true

            for (let i = 0; i < filePaths.length; i++) {
                const filePath = filePaths[i]

                // 上传图片，获取完整的文件信息
                const result = await uploadImage(filePath, props.businessType)
                
                // 存储完整的上传响应对象
                imageList.value.push(result)
            }

            emit('update:modelValue', imageList.value)
            emit('change', imageList.value)

            uni.showToast({
                title: '上传成功',
                icon: 'success'
            })

        } catch (e: any) {
            uni.showToast({
                title: e.message ?? '上传失败',
                icon: 'none'
            })
        } finally {
            uploading.value = false
        }
    }
	
	const openCamera = () => {
	    const input = createNativeInput()
	    // 清除事件监听器（避免重复绑定）
	    input.onchange = null
	    input.onchange = (event: Event) => {
	        const target = event.target as HTMLInputElement
	        if (target.files && target.files.length > 0) {
	            const file = target.files[0]
	            handleFile(file)
	        }
	        // 清除值以便下次选择
	        input.value = ''
	    }
	    // 触发点击
	    input.click()
	}
	
	const handleFile = (file: File) => {
		const blobUrl = URL.createObjectURL(file)
		const result = {
			tempFilePaths: [blobUrl],  // 类似: blob:http://localhost:8080/550e8400-e29b-41d4-a716-446655440000
			tempFiles: [{
				path: blobUrl,
				size: file.size,
				name: file.name,
				type: file.type,
				lastModified: file.lastModified
			}]
		}
		handleUpload(result.tempFilePaths)
	}


    // 选择图片
    const handleChooseImage = (): void => {
		// let inputHtml = createNativeInput();
        if (imageList.value.length >= props.maxCount) {
            uni.showToast({
                title: `最多上传${props.maxCount}张图片`,
                icon: 'none'
            })
            return
        }

        uni.chooseImage({
            count: props.maxCount - imageList.value.length,
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success: (res) => {
                const tempFilePaths = res.tempFilePaths as string[]
                handleUpload(tempFilePaths)
            }
        })
    }

    // 预览图片
    const handlePreview = (index: number): void => {
        uni.previewImage({
            urls: imageUrls.value,
            current: index
        })
    }

    // 删除图片
    const handleDelete = (index: number): void => {
        uni.showModal({
            title: '确认删除',
            content: '确定要删除这张图片吗？',
            success: (res) => {
                const confirm = res.confirm as boolean
                if (confirm) {
                    imageList.value.splice(index, 1)
                    emit('update:modelValue', imageList.value)
                    emit('change', imageList.value)
                }
            }
        })
    }
</script>

<style lang="scss">

    .image {
        &-list {
            flex-direction: row;
            flex-wrap: wrap;
        }

        &-item {
            background-color: #f5f7fa;
            border-radius: 8rpx;
            position: relative;
            width: 160rpx;
            height: 160rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
        }

        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;

        &-delete {
            position: absolute;
            top: 2rpx;
            right: 2rpx;
            width: 44rpx;
            height: 44rpx;
            justify-content: center;
            align-items: center;
        }
    }

    .delete-icon {
        width: 32rpx;
        height: 32rpx;
    }

    .upload {
        &-box {
            background-color: #f5f7fa;
            border-radius: 8rpx;
            width: 160rpx;
            height: 160rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            border: 2rpx dashed #d0d0d0;
            border-radius: 8rpx;
            justify-content: center;
            align-items: center;
        }

        &-icon {
            font-size: 60rpx;
            color: #999999;
            line-height: 60rpx;
            margin-bottom: 10rpx;
        }

        &-text {
            font-size: 24rpx;
            color: #999999;
        }
    }

    .uploading {
        border-style: solid;
        border-color: #d0d0d0;
        background-color: #f5f7fa;
    }
</style>
