<template>
	<div>
		<el-dialog v-model="exportDialogVisible" v-loading="fullscreenLoading" title="导出" width="500" center align-center
			@close="close" draggable>
			<el-form class="formStyle" :rules="rules" ref="formRef" :model="exportObject">
				<el-form-item prop="timeValue">
					<el-date-picker v-model="exportObject.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"
						value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
				<el-form-item prop="spiderType">
					<el-checkbox-group v-model="exportObject.spiderType" class="checkboxStyle">
						<el-checkbox label="DSN数据" value="dsn" />
						<el-checkbox label="ITU数据" value="itu" />
						<el-checkbox label="ST数据" value="spaceTrack" />
					</el-checkbox-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="close">取消</el-button>
					<el-button type="primary" @click="handleExport">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { defineProps } from 'vue';
import axios from 'axios'
import Cookies from 'js-cookie'
import { ElLoading, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface RuleForm {
	//表单字段的类型
	timeValue: string
	spiderType: Array<string>
}
const formRef = ref<FormInstance>()
const rules = ref<FormRules<RuleForm>>({
	timeValue: [
		{
			type: 'date',
			required: true,
			message: '请选择时间段',
			trigger: 'change',
		},
	],
	spiderType: [
		{
			type: 'array',
			required: true,
			message: '请至少选择一种数据类型',
			trigger: 'change',
		},
	]
})
//表单绑定的字段
const exportObject = ref({
	timeValue: "",
	spiderType: []
})
const fullscreenLoading = ref(false)
const props = defineProps({
	dialogVisible: {
		type: Boolean,
		default: false
	}
})
const emit = defineEmits(['update:dialogVisible', 'confirm'])
const exportDialogVisible = ref(props.dialogVisible)

// 导出方法
const handleExport = async () => {
	if (!formRef.value) return
	await formRef.value.validate(async (valid, fields) => {
		console.log('开始校验');
		if (valid) {
			console.log('校验通过');
			const loading = ElLoading.service({
				lock: true,
				text: 'Loading',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			try {
				const res = await axios.post(
					'/api/export/downloadFile',
					{ times: exportObject.value.timeValue, filters: exportObject.value.spiderType },
					{
						responseType: 'blob',
						headers: {
							'Token': Cookies.get('Admin-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' })
				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)
				loading.close()
				close()
				ElMessage.success('导出成功');
			} catch (e) {
				console.error('导出失败', e)
				close()
				ElMessage.error('导出失败');
			}
		} else {
			console.log('校验不通过');
		}
	})


}
// 关闭弹窗的方法
const close = () => {
	formRef.value?.clearValidate()
	exportDialogVisible.value = false
}
// 监听父组件传过来的值
watch(() => props.dialogVisible,
	(newVal) => {
		exportDialogVisible.value = newVal
	}
)
// 监听组件内的值并向父组件更新
watch(() => exportDialogVisible.value,
	(newVal) => {
		emit('update:dialogVisible', newVal)
	}
)



</script>

<style lang="scss" scoped>
.formStyle {
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.checkboxStyle {
	display: flex;
	gap: 30px;
	/* 复选框之间的间距 */
}
</style>