<template>
	<div style="padding: 5px;flex: 1">
		<div>
			<van-uploader
        :disabled="readonly"
        v-model="fileListTemp"
				accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.wps,.et,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*"
				:after-read="uploadFile"
        upload-icon="plus"
        :show-upload="true"
        :before-delete="onDelete"
      />
		</div>
	</div>
</template>


<script setup>
	import { ref, onMounted, getCurrentInstance, watch } from 'vue'
  import { showFailToast, showSuccessToast, showConfirmDialog } from 'vant';
	const { proxy } = getCurrentInstance()

  const emit = defineEmits(['update:firstFileUrl'])

	const props = defineProps({
		fId: {
			type: String,
			default: () => ''
		},
		value1: {
			type: String,
			default: () => null
		},
		value2: {
			type: String,
			default: () => null
		},
		value3: {
			type: String,
			default: () => null
		},
		value4: {
			type: String,
			default: () => null
		},
		value5: {
			type: String,
			default: () => null
		},
		selectButton: {
			type: Boolean,
			default: () => true
		},
		deleteButton: {
			type: Boolean,
			default: () => true
		},
		readonly: {
			type: Boolean,
			default: () => false
		},
		isFile: {
			type: Boolean,
			default: () => false
		}
	})

	onMounted(() => {
		getTableData()
	})

	const tableData = ref([])
	const getTableData = () => {
		//携带自定义参数
		var url = 'framework/Common/queryFileWithValues'
		var param = {
			fId: props.fId, //必填
			value1: props.value1, //非必填
			value2: props.value2, //非必填
			value3: props.value3, //非必填
			value4: props.value4, //非必填
			value5: props.value5, //非必填
		}
		proxy.$axios.get(url, param).then(response => {
			if (response.data.code === 0) {
				tableData.value = response.data.data
        fileListTemp.value = []
        for (let item of tableData.value) {
          fileListTemp.value.push({
            id: item.id,
            url: import.meta.env.VITE_BASE_API + 'framework/Common/downloadFileS3?bucket=' + bucket.value + '&id=' + item.id + '&fullfilename=' + Date.now() + item.fileName
          })
        }
        if (fileListTemp.value.length > 0) {
          emit('update:firstFileUrl', fileListTemp.value[0].url)
        } else {
          emit('update:firstFileUrl', null) // 或 ''
        }

			} else {
				showFailToast('失败！' + response.data.msg)
			}
		})
	}
	const headers = ref({
		token: localStorage.getItem('token'),
		userId: localStorage.getItem('userId')
	})
	const fileListTemp = ref([])
	const bucket = ref(import.meta.env.VITE_BUCKET)

	/* 转成blob */
	import {
		atob
	} from 'js-base64';

	watch(props, (newVal, oldVal) => {
		getTableData()
	})

	const uploadFile = (file) => {
		const formData = new FormData()
		formData.append('fId', props.fId);
		formData.append('bucket', bucket.value);
		formData.append('value1', props.value1);
		formData.append('value2', props.value2);
		formData.append('value3', props.value3);
		formData.append('value4', props.value4);
		formData.append('value5', props.value5);
		formData.append('file', file.file);
		formData.append('fileName', file.file.name);
		var url = 'framework/Common/uploadFileS3'
		proxy.$axios.post(url, formData, 'multipart/form-data').then(response => {
			showSuccessToast('上传成功')
			getTableData()
		}).catch(error => {
			showFailToast('上传失败' + res.data.msg)
		});
	}

	/* 在线删除 */
	const showDialogVisible = ref(false)
	const deleteInfo = ref()
	const handleDelete = (row) => {
		showDialogVisible.value = true
		deleteInfo.value = row
	}

	const onDelete = (file) => {
    console.log(file);
    showConfirmDialog({
      title: '删除照片',
      message:
        '确定删除该照片吗?',
    }).then(() => {
        let url = 'framework/Common/removeFile'
        let param = {
          id: file.id
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code === 0) {
            showSuccessToast('删除成功!')
            getTableData()
          } else {
            showFailToast('删除失败;' + response.data.msg)
          }
        });
        return true
      }).catch(() => {
        return false
      });
	}

	// 获取文件图标类名
	const getFileIconClass = (fileType) => {
		if (fileType === 'pdf') return 'pdf-icon';
		if (fileType === 'image' || fileType === 'jpg' || fileType === 'png' || fileType === 'gif')
			return 'image-icon';
		if (fileType === 'doc' || fileType === 'docx') return 'doc-icon';
		if (fileType === 'xls' || fileType === 'xlsx') return 'excel-icon';
		if (fileType === 'txt') return 'text-icon';
		return 'other-icon';
	}

	// 获取文件图标
	const getFileIcon = (fileType) => {
		if (fileType === 'pdf') return 'description';
		if (fileType === 'image' || fileType === 'jpg' || fileType === 'png' || fileType === 'gif') return 'photo-o';
		if (fileType === 'doc' || fileType === 'docx') return 'notes-o';
		if (fileType === 'xls' || fileType === 'xlsx') return 'chart-trending-o';
		if (fileType === 'txt') return 'document';
		return 'description';
	}

	const convertBytesToSize = (bytes) => {
		const kb = 1024;
		const mb = kb * 1024;

		if (bytes < kb) return bytes + ' B';
		else if (bytes < mb) return (bytes / kb).toFixed(2) + ' KB';
		else return (bytes / mb).toFixed(2) + ' MB';
	}
</script>

<style scoped>
	* {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	body {
		font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
		color: #333;
		line-height: 1.6;
		min-height: 100vh;
	}

	.header h1 {
		font-size: 2.5rem;
		color: #1989fa;
		margin-bottom: 10px;
		text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
	}

	.header p {
		font-size: 1.1rem;
		color: #666;
		max-width: 600px;
		margin: 0 auto;
	}

	.section-title i {
		margin-right: 10px;
		font-size: 1.6rem;
	}

	.table-row {
		background-color: white;
		border-radius: 8px;
		margin-bottom: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		transition: transform 0.2s ease, box-shadow 0.2s ease;
		align-items: center;
	}

	.table-row:hover {
		transform: translateX(5px);
		box-shadow: 0 5px 15px rgba(25, 137, 250, 0.15);
	}

	.file-name {
		font-weight: 500;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.action-buttons {
		display: flex;
		gap: 10px;
		justify-content: flex-start;
	}
</style>
