<!-- ExcelUploadPreview.vue -->
<template>
    <div class="excel-upload-preview">
        <!-- 文件上传 -->
        <el-upload ref="uploadRef" :auto-upload="false" :show-file-list="false" accept=".xlsx,.xls,.csv"
            :before-upload="handleBeforeUpload" @change="handleFileChange">
            <el-button type="primary">选择 Excel 文件</el-button>
            <span v-if="fileName" class="ml-2">已选择：{{ fileName }}</span>
        </el-upload>

        <!-- 解析消息 -->
        <el-alert v-if="parseMessage" :title="parseMessage" :type="parsedValid ? 'success' : 'warning'"
            style="margin-top: 12px" />

        <!-- 错误信息 -->
        <el-alert v-if="errorMessages.length" :closable="false" type="error" style="margin-top: 12px">
            <template #default>
                <div v-for="(msg, idx) in errorMessages" :key="idx">{{ msg }}</div>
            </template>
        </el-alert>

        <!-- 表格 -->
        <el-table v-if="editableData.length" :data="editableData" style="width: 100%; margin-top: 16px" border
            max-height="400" size="small">
            <!-- 动态列 -->
            <el-table-column v-for="header in headers" :key="header" :prop="header" :label="getHeaderLabel(header)"
                min-width="120">
                <template #default="{ row, $index }">
                    <el-input v-if="editRowIndex === $index && editColumn === header" v-model="row[header]"
                        @blur="saveEdit" @keyup.enter="saveEdit" ref="currentInput" />
                    <span v-else @click="startEdit($index, header)">
                        {{ row[header] ?? '' }}
                    </span>
                </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ $index }">
                    <el-button v-if="editRowIndex === $index" type="text" size="small" @click="cancelEdit">
                        取消
                    </el-button>
                    <el-button v-else type="text" size="small" @click="startEdit($index, headers[0])">
                        编辑
                    </el-button>
                    <el-button type="text" size="small" style="color: #f56c6c" @click="deleteRow($index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 提交按钮 -->
        <el-button v-if="showConfirm && editableData.length" type="success" style="margin-top: 16px"
            :loading="submitting" @click="handleSubmit">
            确认提交（共 {{ editableData.length }} 条）
        </el-button>
    </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
    showConfirm: { type: Boolean, default: true },
    beforeUpload: { type: Function, default: null },
    headerRow: { type: Number, default: 0 },
    checkStartRow: { type: Number, default: 3},
    requiredFields: { type: String, default: '' },
    useChineseHeader: { type: Boolean, default: true },
    transformSubmitData: {
        type: Function,
        default: (rows) => rows
    }
})

const emit = defineEmits(['submit', 'parsed'])

// refs
const uploadRef = ref(null)
const currentInput = ref(null)
const fileName = ref('')
const headers = ref([])
const chineseHeadersMap = ref({})
const editableData = ref([]) // ✅ 所有操作在此数组上进行
const editRowIndex = ref(-1)
const editColumn = ref(null)
const parseMessage = ref('')
const parsedValid = ref(true)
const errorMessages = ref([])
const submitting = ref(false)

// 获取表头显示文本
const getHeaderLabel = (header) => {
    return props.useChineseHeader ? (chineseHeadersMap.value[header] || header) : header
}

// 上传前校验
const handleBeforeUpload = (file) => {
    if (props.beforeUpload && !props.beforeUpload(file)) return false
    if (!/\.(xlsx|xls|csv)$/i.test(file.name)) {
        ElMessage.error('仅支持 Excel 或 CSV 文件')
        return false
    }
    return true
}

// 解析文件
const handleFileChange = async (uploadFile) => {
    const file = uploadFile.raw
    if (!file) return

    fileName.value = file.name
    parseMessage.value = ''
    parsedValid.value = true
    errorMessages.value = []
    chineseHeadersMap.value = {}

    const formData = new FormData()
    formData.append('file', file)
    formData.append('headerRow', props.headerRow.toString())
    formData.append('checkStartRow', props.checkStartRow.toString())
    if (props.requiredFields.length > 0) {
        formData.append('requiredFields', props.requiredFields)
    }

    try {
        const res = await request.post('/oss/api/excel/import', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })

        if (res.code !== 200 || !res.data?.success) {
            throw new Error(res.msg || '解析失败')
        }

        const parsed = res.data
        parseMessage.value = parsed.message || ''
        parsedValid.value = parsed.valid !== false
        errorMessages.value = parsed.errorMessages || []

        const rawData = parsed.data || []
        headers.value = parsed.headers || []

        if (rawData.length === 0) {
            editableData.value = []
        } else {
            if (props.useChineseHeader) {
                const firstRow = rawData[0]
                const map = {}
                headers.value.forEach(key => {
                    map[key] = firstRow[key] || key
                })
                chineseHeadersMap.value = map
                editableData.value = rawData.slice(1).map(row => ({ ...row }))
            } else {
                editableData.value = rawData.map(row => ({ ...row }))
            }
        }

        emit('parsed', editableData.value)
        uploadRef.value.clearFiles()
    } catch (err) {
        console.error('Parse error:', err)
        ElMessage.error('文件解析失败：' + (err.message || ''))
    }
}

// 开始编辑
const startEdit = (index, column) => {
    editRowIndex.value = index
    editColumn.value = column
    nextTick(() => {
        currentInput.value?.focus()
    })
}

// 保存编辑
const saveEdit = () => {
    editRowIndex.value = -1
    editColumn.value = null
}

// 取消编辑
const cancelEdit = () => {
    // 无需回滚，因为我们直接操作 editableData（无原始快照）
    // 如果需要“撤销到初始状态”，可保留 originalData
    saveEdit()
}

// 删除行
const deleteRow = (index) => {
    ElMessageBox.confirm('确定删除此行？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        editableData.value.splice(index, 1)
        // 重置编辑状态（避免索引错乱）
        if (editRowIndex.value === index) {
            editRowIndex.value = -1
            editColumn.value = null
        } else if (editRowIndex.value > index) {
            editRowIndex.value-- // 索引前移
        }
    }).catch(() => { })
}

// 提交最终数据
const handleSubmit = () => {
    if (editableData.value.length === 0) {
        ElMessage.warning('没有可提交的数据')
        return
    }

    submitting.value = true
    try {
        // 调用 transformSubmitData 进行格式转换（如类型转换）
        const finalData = props.transformSubmitData([...editableData.value])
        emit('submit', finalData)
    } catch (err) {
        ElMessage.error('提交失败：' + (err.message || ''))
    } finally {
        submitting.value = false
    }
}
</script>

<style scoped>
.ml-2 {
    margin-left: 8px;
}
</style>