<template>
	<el-dialog title="导入产品" v-model="isShowDialog" width="500px" destroy-on-close @close="handleDialogClose">
		<div class="import-container">
			<!-- 文件上传区域 -->
			<el-upload
				ref="uploadRef"
				class="upload-demo"
				drag
				:action="uploadAction"
				:headers="uploadHeaders"
				:data="uploadData"
				:accept="acceptFileTypes"
				:limit="1"
				:on-success="handleUploadSuccess"
				:on-error="handleUploadError"
				:before-upload="beforeUpload"
				:on-exceed="handleExceed"
				:on-remove="handleRemove"
				:show-file-list="true"
				:auto-upload="false" <!-- 手动触发上传 -->
			>
				<div class="el-upload-area">
					<el-icon class="el-icon--upload">
						<UploadFilled />
					</el-icon>
					<div class="el-upload__text">将ZIP文件拖到此处，或<em>点击上传</em></div>
					<div class="el-upload__tip">上传ZIP文件批量导入产品（TXT格式）</div>
				</div>
			</el-upload>

			<!-- 导入说明 -->
			<div class="import-instructions mt20">
				<el-card shadow="never" class="box-card">
					<template #header>
						<div class="card-header">
							<span>导入说明</span>
						</div>
					</template>
					<el-text type="info" size="small">
						<ul class="instruction-list">
							<li>1. 请上传包含TXT格式产品数据的ZIP压缩包</li>
							<li>2. 文件编码请使用UTF-8</li>
							<li>3. 文件大小不能超过 {{ fileSizeLimit }}MB</li>
							<li>4. 导入前请确保数据格式正确</li>
						</ul>
					</el-text>
				</el-card>
			</div>

			<!-- 导入结果展示 -->
			<div v-if="importResult" class="import-result mt20">
				<el-alert
					:title="importResult.success ? '导入完成' : '导入失败'"
					:type="importResult.success ? 'success' : 'error'"
					:closable="false"
					show-icon
				>
					<template v-if="importResult.success">
						<div>成功导入 {{ importResult.data.failCount === 0 ? '所有' : '部分' }} 产品数据</div>
						<div v-if="importResult.data.failCount > 0">
							失败 {{ importResult.data.failCount }} 条记录
						</div>
						<div v-if="importResult.data.failReasons && importResult.data.failReasons.length > 0">
							<el-collapse>
								<el-collapse-item title="查看失败原因">
									<div v-for="(reason, index) in importResult.data.failReasons" :key="index">
										{{ reason }}
									</div>
								</el-collapse-item>
							</el-collapse>
						</div>
					</template>
					<template v-else>
						<div>{{ importResult.message }}</div>
					</template>
				</el-alert>
			</div>
		</div>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleCancel">取消</el-button>
				<el-button type="primary" :loading="loading" @click="handleSubmitUpload">
					{{ loading ? '导入中...' : '开始导入' }}
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox, type UploadInstance, type UploadFile } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { importProduct } from '/@/api/customerService/product';

const emit = defineEmits<{
	(e: 'getProductList'): void;
}>();

const isShowDialog = ref(false);
const loading = ref(false);
const uploadRef = ref<UploadInstance>();
const importResult = ref<any>(null);

// 上传配置
const uploadAction = '/api/customerService/product/import';
const uploadHeaders = reactive({
	Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
});
const uploadData = reactive({});
const acceptFileTypes = '.zip,.ZIP';
const fileSizeLimit = 50;

/**
 * 打开对话框
 */
const openDialog = () => {
	isShowDialog.value = true;
	loading.value = false;
	importResult.value = null;
};

/**
 * 处理对话框关闭
 */
const handleDialogClose = () => {
	uploadRef.value?.clearFiles();
	importResult.value = null;
};

/**
 * 取消操作
 */
const handleCancel = () => {
	isShowDialog.value = false;
};

/**
 * 上传前校验
 */
const beforeUpload = (file: File): boolean => {
	const isZip = file.type === 'application/zip' || file.name.toLowerCase().endsWith('.zip');
	const isLtLimit = file.size / 1024 / 1024 < fileSizeLimit;

	if (!isZip) {
		ElMessage.error('请上传ZIP格式的压缩包文件!');
		return false;
	}

	if (!isLtLimit) {
		ElMessage.error(`文件大小不能超过${fileSizeLimit}MB!`);
		return false;
	}

	importResult.value = null;
	return true;
};

/**
 * 处理文件超出限制
 */
const handleExceed = () => {
	ElMessage.warning('只能上传一个文件，请先删除当前文件');
};

/**
 * 处理文件移除
 */
const handleRemove = () => {
	importResult.value = null;
};

/**
 * 手动提交上传
 */
const handleSubmitUpload = async () => {
	const fileList = uploadRef.value?.uploadFiles;
	if (!fileList || fileList.length === 0) {
		ElMessage.warning('请先选择要上传的ZIP文件');
		return;
	}

	try {
		await ElMessageBox.confirm(
			'确认导入选中的产品数据吗？',
			'导入确认',
			{
				confirmButtonText: '确认导入',
				cancelButtonText: '取消',
				type: 'warning',
			}
		);

		loading.value = true;
		importResult.value = null;
		
		const file = fileList[0].raw!;
		await handleCustomUpload(file);
		
	} catch {
		loading.value = false;
	}
};

/**
 * 自定义上传处理
 */
const handleCustomUpload = async (file: File) => {
	try {
		// 调用导入接口
		const response = await importProduct(file);
		
		// 根据API文档，响应结构为: { failCount: number, failReasons: string[] }
		if (response.code === 200) {
			importResult.value = {
				success: true,
				data: response.data,
				message: '导入成功'
			};
			
			ElMessage.success(`导入完成！失败记录：${response.data.failCount}条`);
			emit('getProductList');
			
			// 3秒后自动关闭
			setTimeout(() => {
				if (isShowDialog.value && response.data.failCount === 0) {
					isShowDialog.value = false;
				}
			}, 3000);
		} else {
			throw new Error(response.message || '导入失败');
		}
		
	} catch (error: any) {
		importResult.value = {
			success: false,
			message: error.message || '导入失败'
		};
		ElMessage.error(`导入失败：${error.message || '未知错误'}`);
	} finally {
		loading.value = false;
	}
};

// 保留原有方法用于自动上传模式
const handleUploadSuccess = (response: any) => {
	// 处理自动上传的成功响应
};

const handleUploadError = (error: any) => {
	// 处理自动上传的错误
};

defineExpose({ openDialog });
</script>