<template>
	<view>
		<view v-if="props.modelValue && props.modelValue.length" @click="open(true)" class="flex gap-2 overflow-x-auto">
			<view class=" border-gray-100 border-solid flex rounded-[14px] relative"
				v-for="img of (Array.isArray(props.modelValue) ? props.modelValue : [props.modelValue])" :key="img">
				<wd-img mode="aspectFill" radius="10" :width="width" :height="height" :src="img" />
			</view>
		</view>

		<view v-else @click="open(true)" class="flex gap-2 overflow-x-auto">
			<view
				:style="{
					width: width + 'px',
					height: height + 'px',
				}"
				class=" border-gray-100 border-solid flex rounded-[14px] relative  flex-col items-center justify-center">
				<wd-icon name="image" size="28px"></wd-icon>
				<view class="mt-2 font-bold text-[12px]" v-if="height > 70">请选择</view>
			</view>
		</view>

		<wd-popup :z-index="998" v-model="show" closable position="left" custom-style="width: 86vw;" @close="close(false)">
			<view class="pop yUpload h-dvh overflow-hidden">
				<view class="bg-white overflow-hidden h-full" style="background-clip: content-box;">

					<view class="bg-gray-100 p-4 flex">
						<view class="mr-4">
							<wd-button type="warning" @tap="chooseFile">上传文件</wd-button>
						</view>
						<view>
							<wd-button @tap="ok">确认选择</wd-button>
						</view>
					</view>

					<view v-if="LArr.length" class="shadow-lg ">
						<view class="text px-2 mt-3 font-bold">已选择 ( {{ LArr.length || 0 }} / {{ size }} 张)</view>
						<view class="bg-gray images flex gap-2 overflow-x-auto p-4 pt-2 ">
							<view @click="onClickCheck({ url: img })" class=" border-gray-100 border-solid flex rounded-[14px] relative"
								v-for="img of LArr" :key="img">
								<wd-img mode="aspectFill" radius="10" :width="100" :height="100" :src="img" />

								<view class="absolute bg-white opacity-80 inset-0 flex items-center justify-center border-spacing-1">取消选择
								</view>

							</view>
						</view>
					</view>
					<view v-else class="shadow-lg ">
						<view class="text p-3 font-bold">可选择 ({{ size }} 张)</view>
					</view>

					<view class="overflow-hidden rounded-t-3xl">
						<yList ref="yListRef" :apiObj="system.resourcesList">
							<template #default="{ list }">

								<view class="grid grid-cols-2 gap-4 p-4 overflow-hidden rounded-t-3xl">
									<view
										class="relative flex flex-col items-center justify-center bg-gray-100 p-4 rounded-md overflow-hidden"
										v-for="item of list" :key="item.id" v-show="item.type === 1">
										<view class="list-item-img" @click="onClickCheck(item)" v-if="item.type === 1"
											:style="{ backgroundImage: 'url(' + item.url + ')' }"></view>
										<view class="list-item-img" @dblclick="onClickDir(item)" v-if="item.type === 3"
											:style="{ backgroundImage: 'url(' + folderPng + ')' }"></view>
										<view class="list-item-name">{{ item.name }}</view>

										<view @click="onClickCheck(item)"
											class="absolute bg-white opacity-80 inset-2 flex items-center justify-center border-spacing-1"
											v-if="LArr.includes(item.url)">取消选择</view>

									</view>
								</view>

							</template>
						</yList>
					</view>
				</view>
			</view>

		</wd-popup>

	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import system from '@/api/modules/system.js'
import yList from "/components/yList/index.vue"
import folderPng from '@/assets/images/folder.png'
import { uploadImage } from '@/utils/request';
const yListRef = ref(null)

const formData = ref({
	parent_id: 0,
	type: "image",
})

const chooseFile = async () => {
	uni.chooseImage({
		count: 1, // 默认9
		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album'], // 从相册选择
		success: async (res) => {
			try {
				if (!res.tempFilePaths || !res.tempFilePaths.length) {
					throw new Error('未选择文件或文件路径无效。');
				}

				const filePath = res.tempFilePaths[0];
				const result = await uploadImage({ filePath, formData: formData.value, name: "image" })
				console.log('成功上传图片：', result);

				yListRef.value.upData()

				// 根据需要处理结果
			} catch (error) {
				console.error('选择文件或上传图片时出错：', error.message);
				// 处理错误
			}
		}
	});
}

const emit = defineEmits(['update:modelValue']);
const props = defineProps({
	modelValue: {
		type: String,
		default: ""
	},
	size: {
		type: Number,
		default: 1
	},
	width: {
		type: Number,
		default: 100
	},
	height: {
		type: Number,
		default: 100
	},
})

const LArr = ref([])

const show = ref(false)
const open = (O) => {
	show.value = O

	if (O && yListRef.value?.upData) {
		yListRef.value.upData()
	}

	if (props.modelValue) {
		if (Array.isArray(props.modelValue)) {
			LArr.value = JSON.parse(JSON.stringify(props.modelValue))
		} else {
			LArr.value = [props.modelValue]
		}
	}

}
open(false)

const close = () => {
	// LArr.value = []
}

const ok = () => {
	if (props.size == 1) {
		emit("update:modelValue", LArr.value.pop())
	} else {
		emit("update:modelValue", LArr.value)
	}

	show.value = false
}

const onClickCheck = (row) => {
	const index = LArr.value.findIndex(item => item === row.url)


	if (index > -1) {
		LArr.value.splice(index, 1)
	} else {
		if (props.size > LArr.value.length) {
			LArr.value.unshift(row.url)
		} else {
			uni.showToast({
				title: `已选择 ${LArr.value.length} 张`,
				icon: 'none'
			})

			console.log(`已选择 ${LArr.value.length} 张`);
		}

	}
}


</script>

<style lang="scss">
.list-item-img {
	width: 100%;
	height: 80px;
	background-position: center center;
	background-size: contain;
	background-repeat: no-repeat;
}

.list-item-name {
	text-align: center;
	padding: 5px 10px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	font-size: 12px;
	width: 100%;
}

.pop {
	// position: fixed;
	background: rgba(0, 0, 0, 0.256);
	background-clip: border-box;
	overflow: hidden;
	inset: 0px;
}
</style>
