<template>
	<el-dialog v-model="exportDialogVisible" title="导出" width="400" center align-center @close="close" draggable>
		<div class="text-center p-0 gap-3">
			<!-- <span style="color: #fff;font-size: 15px;">请选择导出数据时间与数据类型。</span>
			<br> -->
			<el-date-picker v-model="timeValue" type="datetimerange" format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始时间"
				end-placeholder="结束时间" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" style="width: 280px"
				value-format="YYYY-MM-DD HH:mm:ss" />
			<el-checkbox-group v-model="checkList">
				<el-checkbox label="DSN数据" value="dsn" />
				<el-checkbox label="ITU数据" value="itu" />
				<el-checkbox label="ST数据" value="spaceTrack" />
			</el-checkbox-group>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="close">取消</el-button>
				<el-button type="primary" @click="handleExport">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { defineProps } from 'vue';
import { exportSpiderData } from '@/api/spiderData';
import axios from 'axios'
const props = defineProps({
	dialogVisible: {
		type: Boolean,
		default: false
	},
	mode: {
		type: String,
		default: '1'
	}
})
const emit = defineEmits(['update:dialogVisible', 'confirm'])
const exportDialogVisible = ref(props.dialogVisible)
const checkList = ref([])
const timeValue = ref('')
// 导出方法
const handleExport = async () => {
	// exportSpiderData({ times: timeValue.value, filters: checkList.value })

  try {
    const res = await axios.post(
      '/api/export/downloadFile',
      { times: timeValue.value, filters: checkList.value },
      {
        responseType: 'blob',
        headers: {
            'Token': localStorage.getItem('token') || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzU5MjA5NzM4fQ.6hVko0EQTuz7OYjXEafZYLpmkVEyiLhZ8aWHi0Pni_s', // 根据你的 token 存储方式调整
        },
      }
    )
    // 获取文件名
    const disposition = res.headers['content-disposition']
    let fileName = 'export.zip'
    if (disposition) {
      const match = disposition.match(/filename="?([^"]+)"?/)
      if (match) fileName = decodeURIComponent(match[1])
    }
    const blob = new Blob([res.data], { type: 'application/zip' })
    console.log(blob.type, blob.size);

    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
  } catch (e) {
      console.error('导出失败', e)
  }
}
// 关闭弹窗的方法
const close = () => {
	exportDialogVisible.value = false
}
// 监听父组件传过来的值
watch(() => props.dialogVisible,
	(newVal) => {
		exportDialogVisible.value = newVal
	}
)
// 监听组件内的值并向父组件更新
watch(() => exportDialogVisible.value,
	(newVal) => {
		emit('update:dialogVisible', newVal)
	}
)

// const triggerDownload = (blobData: any) => {
// 	const zipFile = new File([blobData], 'archive.zip', {
// 		type: 'application/zip',
// 	});
// 	console.log(zipFile);
// 	const fileUrl = URL.createObjectURL(zipFile);

// 	// 创建下载链接
// 	const downloadLink = document.createElement('a');
// 	downloadLink.href = fileUrl;
// 	// 使用File对象的名称作为下载文件名
// 	downloadLink.download = zipFile.name;

// 	// 将链接添加到页面并触发点击
// 	document.body.appendChild(downloadLink);
// 	downloadLink.click();

// 	// 清理资源
// 	setTimeout(() => {
// 		// 移除链接元素
// 		document.body.removeChild(downloadLink);
// 		// 释放临时URL
// 		URL.revokeObjectURL(fileUrl);
// 	}, 0);
// }

// const aaa = (res: any) => {
// 	// const blob = new Blob([res], { type: 'application/zip' })
// 	// const link = document.createElement('a')
// 	// link.style.display = 'none'
// 	// link.href = URL.createObjectURL(blob)
// 	// link.setAttribute('download', `${'111'}.zip`)
// 	// document.body.appendChild(link)
// 	// link.click()
// 	// document.body.removeChild(link)

// 	// const url = window.URL.createObjectURL(new Blob([res], { type: "application/zip" }))
// 	// const link = document.createElement('a')
// 	// link.style.display = 'none'
// 	// link.href = url
// 	// link.setAttribute('download', '222.zip')
// 	// document.body.appendChild(link)
// 	// link.click()
// 	// document.body.removeChild(link)

// 	const url = window.URL.createObjectURL(res);
// 	const a = document.createElement('a');
// 	a.style.display = 'none';
// 	a.href = url;
// 	a.download = 'example.zip';
// 	document.body.appendChild(a);
// 	a.click();
// 	window.URL.revokeObjectURL(url);

// }
// function downloadZipFromBinary(binaryString: any, fileName: string) {
// 	try {
// 		if (!fileName.endsWith('.zip')) {
// 			fileName += '.zip';
// 		}

// 		const uint8Array = new Uint8Array(binaryString);
// 		const blob = new Blob([uint8Array], { type: 'application/zip' });
// 		const url = URL.createObjectURL(blob);

// 		const a = document.createElement('a');
// 		a.href = url;
// 		a.download = fileName;
// 		document.body.appendChild(a);
// 		a.click();

// 		setTimeout(() => {
// 			document.body.removeChild(a);
// 			URL.revokeObjectURL(url);
// 		}, 100);

// 	} catch (error) {
// 		console.error('下载ZIP文件时发生错误:', error);
// 		throw error;
// 	}
// }



</script>